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@lists.isocpp.org>
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@lists.isocpp.org;
CC: Frederick Virchanza Gotham <cauldwell.thomas@gmail.com>;
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@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals