Search code examples
c++undefined-behaviorlifetimestrict-aliasingc++23

Implementation of std::start_lifetime_as()


After P0593R6 ('Implicit creation of objects for low-level object manipulation') was accepted in C++20, C++23 will get std::start_lifetime_as() which 'completes the functionality proposed in [P0593R6]' (cf. P2590R2, P2679R2 and the cppreference C++ 23 feature testing page).

How could a reference implementation of std::start_lifetime_as() look like?

Would something like this be sufficient, or is there more to it?

#include <cstddef>
#include <new>

template<class T>
    T* start_lifetime_as(void* p) noexcept
{
    new (p) std::byte[sizeof(T)];
    return static_cast<T*>(p);
}

Solution

  • These functions are purely compiler magic: there is no way to implement these effects in C++ (strictly construed), which is why they were added to the library.

    Implementations have often "looked the other way", or been unable to prove that undefined behavior was occurring, but it was only a matter of time before they caught on to any given example and "miscompiled" it.