mardi 26 juillet 2016

What is the most idiomatic way to "delay" the construction of a C++ object?

For built-in types, like int, you can delay the initialization simply writing nothing. Is there a way to do the same for C++ objects?

I wrote this code that does the job, but I was wondering if there is an idiomatic way. If so, what is it? Was it even possible before the introduction of aligned storage?

#include <utility>                                                      
#include <type_traits>                                                  

template <typename T>                                                   
struct delayed {                                                        
    template <typename...Args> void init(Args&&... args) {              
        new ( memory() ) T(std::forward<Args>(args)...);                
    }                                                                   

    operator T*() {                                                     
        return memory();                                                
    }                                                                   

    ~delayed() {                                                        
        memory()->~T();                                                 
    }                                                                   

private:                                                                
    T* memory() { return reinterpret_cast<T*>(&bytes_); }               
    typename std::aligned_storage<sizeof(T), alignof(T)>::type bytes_{};
};                                                                      

This code assumes in all possible ways you arrive to the destructor the init function has been called. Depending on the use, it can be better to put a "built" flag.

Aucun commentaire:

Enregistrer un commentaire