Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Allocate Storage for Object without Initializing it?

Tags:

c++

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.

like image 663
Max Avatar asked Nov 29 '25 20:11

Max


1 Answers

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));
    }
};
like image 115
CouchDeveloper Avatar answered Dec 03 '25 02:12

CouchDeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!