C++ Logo

std-proposals

Advanced search

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

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Thu, 24 Jul 2025 10:04:52 +0100
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);
    }

Received on 2025-07-24 09:05:07