C++为对象分配存储而不对其进行初始化

C++ Allocate Storage for Object without Initializing it?

本文关键字:初始化 对象 分配 存储 C++      更新时间:2023-10-16

是否有一个公认的习惯用法来就地为对象分配后备存储但不初始化它? 这是我幼稚的解决方案:

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

我的直接用例是对象池,但它也会更普遍地有用。

在 C++11 中,您可以使用 std::aligned_storage(另请参阅):

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