Using a C++ union for uninitialized memory

3 weeks ago 7
ARTICLE AD BOX

I am needing to manage memory for object allocation manually. I have been using a alignas(T) char storage[] array with dynamic casts. But what I really want is an array of uninitialized values.

Can I write a template union like this:

template<typename T> union uninitialized { T value; uninitialized() {} ~uninitialized() {} };

It seems to work:

uninitialized<Foo> data[10]; std::construct_at(std::addressof(data[0].value), /* ctor args ... */); // ... std::destroy_at(std::addressof(data[0].value));

Even for a class Foo with non-trivial constructor & destructor.

But just because it works doesn't mean I am avoiding undefined behavior. Is this code well defined in C++ (I am targeting C++20 and above).

Read Entire Article