r/cpp • Antimodern C++, Embedded, Audio • Aug 05 '25

Why still no start_lifetime_as?

C++ has desperately needed a standard UB-free way to tell the compiler that "*ptr is from this moment on valid data of type X, deal with it" for decades. C++23 start_lifetime_as promises to do exactly that except apparently no compiler supports it even two years after C++23 was finalized. What's going on here? Why is it apparently so low priority? Surely it can't be a massive undertaking like modules (which require build system coordination and all that)?

107 Upvotes

64 comments sorted by

View all comments

6

u/pavel_v Aug 06 '25

We are using the below implementation which is "stolen" from this talk

template <typename T>                                                           
[[nodiscard]] T* start_lifetime_as(void* mem) noexcept                          
{                                                                               
    auto bytes = new (mem) unsigned char[sizeof(T)];                            
    auto ptr   = reinterpret_cast<T*>(bytes);                                   
    (void)*ptr;                                                                 
    return ptr;                                                                 
}                                                                               
template <typename T>                                                           
[[nodiscard]] const T* start_lifetime_as(const void* mem) noexcept              
{                                                                               
    const auto mp    = const_cast<void*>(mem);                                  
    const auto bytes = new (mp) unsigned char[sizeof(T)];                       
    const auto ptr   = reinterpret_cast<const T*>(bytes);                       
    (void)*ptr;                                                                 
    return ptr;                                                                 
} 

5

u/viatorus Aug 06 '25

How much does your assembly code change if you simplify this implementation of start_lifetime_as(...) to a simple reinterpret_cast<T*>(mem)?