using T = /* some object type */; struct S { bool is_initialized = false; alignas(T) unsigned char maybe_T[sizeof(T)]; void construct_the_T(int arg) { assert(!is_initialized); new (&maybe_T) T(arg); is_initialized = true; } T& get_the_T() { assert(is_initialized); return reinterpret_cast<T&>(maybe_T); } ~S() { if (is_initialized) { get_the_T().~T(); // destroy the T } } // ... lots of code ... };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter