C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Similar to [[no_discard]], but store in a variable, maybe call it [[must_store]]

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Thu, 24 Jul 2025 11:10:07 +0200
reloc obj;   has the added advantage of disallowing the use of the variable afterwards.   -----Ursprüngliche Nachricht----- Von:Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> Gesendet:Do 24.07.2025 11:05 Betreff:Re: [std-proposals] Similar to [[no_discard]], but store in a variable, maybe call it [[must_store]] An:std-proposals_at_[hidden]; CC:Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>; On Thu, Jul 24, 2025 at 9:00 AM Simon Schröder > I want to bring back an idea from Rust: It has a drop() function which will > call the destructor of an object immediately (and thus officially ends the > lifetime of an object). It better states the goal of ending the lifetime explicitly > than nested scopes. > > I would say that drop() is longer than scopes (at least number of keystrokes), > but it is one less line to read. Maybe it is not short, but it is concise. And I > would claim it is much prettier than scopes. If the type is movable, then:    #include <type_traits>         // remove_const, remove_reference    template<typename TParam>    void drop(TParam &arg)    {        typedef std::remove_const_t< std::remove_reference_t<TParam> > T;        // T might be volatile        T &obj = const_cast<T&>(arg);        (void)T{ static_cast<T&&>(obj) };    }    #include <string>    int main(void)    {        std::string const m;       drop(m);    } If it's not movable, then maybe something like:    #include <cstring>             // memset    #include <memory>              // construct_at    #include <type_traits>         // is_default_constructible, remove_const, remove_reference    template<typename TParam>    void drop(TParam &arg)    {        typedef std::remove_const_t< std::remove_reference_t<TParam> > T;        // T might be volatile        T &obj = const_cast<T&>(arg);        obj.~T();  // just let it throw if it throws        if constexpr ( std::is_default_constructible_v<T> )        {            try            {                std::construct_at<T>(&obj);                return;            }            catch(...){}        }        std::memset(&obj,0,sizeof obj);    // desperate backup plan    }    #include <mutex>    int main(void)    {        std::mutex const m;        drop(m);    } -- Std-Proposals mailing list Std-Proposals_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-07-24 09:19:56