C ++ Allocate storage for an object without initializing it?

Is there an accepted idiom for hosting a backup storage for an object in place, but not for initializing it? Here is my naive solution:

#include <utility>

template<typename T> 
union Slot {
    T inst;

    Slot() {}
    ~Slot() {}

    template<typename... Args>
    T* init(Args&&... args) { return new(&inst) T(std::forward<Args>(args) ...); }
    void release() { inst.~T(); }
};

My immediate use case is for an object pool, but it will also be more useful.

+3
source share
1 answer

In C ++ 11 you can use std::aligned_storage( see also ):

template<typename T> 
struct Slot {
    typename std::aligned_storage<sizeof(T)>::type _storage;

    Slot() {}
    ~Slot() { 
       // check if destroyed!
       ...
    }

    template<typename... Args>
    T* init(Args&&... args) { 
        return new(address()) T(std::forward<Args>(args) ...); 
    }

    void release() { (*address()).~T(); }

    T* address()  {
        return static_cast<T*>(static_cast<void*>(&_storage));
    }
};
+4
source

All Articles