Max
Max

Reputation: 101

C++ Allocate Storage for Object without Initializing it?

Is there an accepted idiom for allocating the backing store for an object in-place but not initializing it? Here's 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 would also be more generally useful.

Upvotes: 3

Views: 325

Answers (1)

CouchDeveloper
CouchDeveloper

Reputation: 19106

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));
    }
};

Upvotes: 4

Related Questions