3 ms·
This is exactly how C++ work. union { MyObject space; }; // just a bunch of bytes MyObject * myObject = new(&space) MyObject(); // invoke the constructo
by gpderetta 4y ago
This is exactly how C++ work.
union { MyObject space; }; // just a bunch of bytes
MyObject * myObject = new(&space) MyObject(); // invoke the constructor
myObject->~MyObject(); // invoke the destructor
If you want RAII use some wrapper like Optional.
- nextaccountic 4y agoIs this syntax new(&something) a new addition? I don't remember it, but then I used to program in C++03
- spacechild1 4y agoIt's been around since forever, precisely because you sometimes need to construct an object in pre-existing storage. Otherwise you couldn't implement std::vector, for example.
- BenFrantzDale 4y agoI assume it’s been around forever. https://en.cppreference.com/w/cpp/language/new https://en.cppreference.com/w/cpp/language/new (Placement-new is the thing you are talking about.) C++20 has `std::construct_at` which does the same thing but is usable at compile time (in a `constexpr` context) https://en.cppreference.com/w/cpp/memory/construct_at https://en.cppreference.com/w/cpp/memory/construct_at
- gpderetta 4y agoTIL about std::construct_at, thanks! edit: not sure why they didn't just bless placement new with constexpr powers though.
- pjmlp 4y agoPlacement new was already a thing in C++ARM.