Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;为对象分配存储而不初始化它?_C++ - Fatal编程技术网

C++ C++;为对象分配存储而不初始化它?

C++ C++;为对象分配存储而不初始化它?,c++,C++,是否有一种公认的习惯用法,用于就地为对象分配备份存储,但不初始化它?以下是我天真的解决方案: #include <utility> template<typename T> union Slot { T inst; Slot() {} ~Slot() {} template<typename... Args> T* init(Args&&... args) { return new(&in

是否有一种公认的习惯用法,用于就地为对象分配备份存储,但不初始化它?以下是我天真的解决方案:

#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(); }
};
#包括
模板
活接头槽{
T inst;
插槽(){}
~Slot(){}
模板
T*init(Args&&…Args){returnnew(&inst)T(std::forward(Args)…);}
无效释放(){inst.~T();}
};

我的即时用例是针对对象池的,但它通常也更有用。

在C++11中,您可以使用
std::aligned_存储
():

模板
结构槽{
typename std::aligned_storage::type_storage;
插槽(){}
~Slot(){
//检查是否已销毁!
...
}
模板
T*init(Args&&…Args){
返回新的(地址())T(std::forward(args)…);
}
void release(){(*address()).~T();}
T*地址(){
返回静态转换(静态转换(&U存储));
}
};

我想你想要的是所谓的。@DVNRS他正在使用新的布局。这段代码在我看来很好。@user3286380确实。。。很抱歉我没有仔细看代码。那问题是什么?分配内存的方法有很多种?或者,在C++11中,
alignas(T)char inst[sizeof(T)]?@dvnrrs我想问题是他的解决方案是否可行。@Max注意到这个类使用起来可能很危险!你应该使它更安全,使用更方便;)至少它是一个私有的内部类型,所以原则上危险只潜伏在接口后面。
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));
    }
};