所以我构建了一个类,我打算用它std::aligned_storage来存储最多16个字节的不同类型的'Variant'类.从理论上讲,它应该能够存储任何POD类型和常见的容器,如std::string和std::map.
我按照这里找到的代码示例进行了操作,看起来它的确是为了我正在寻找的内容:http://en.cppreference.com/w/cpp/types/aligned_storage
我的版本,基本上:
class Variant {
public:
Variant() { /* construct */ }
Variant(std::map<int,int> v) {
new(&m_data) std::map<int,int>(v); // construct std::map<int,int> at &m_data
m_type = TYPE_MAP;
}
~Variant() {
if (m_type == TYPE_MAP) {
// cool, now destruct..?
reinterpret_cast<std::map<int, int>*>(&m_data)->~/*???????????????*/();
}
}
private:
// type of object in m_data
enum Type m_type;
// chunk of space for allocating to
std::aligned_storage<16, std::alignment_of<std::max_align_t>::value>::type m_data;
};
Run Code Online (Sandbox Code Playgroud)
我的问题伴随着破坏.正如你所看到的/*???????????????*/,我不知道~T()在cppreference.com示例中代替什么代码:
reinterpret_cast<const T*>(data+pos)->~T(); // I did the same thing except I know what T is, is that a problem is it?
Run Code Online (Sandbox Code Playgroud)
在我看来,我正在做同样的事情,无视模板匿名.问题是,std::map没有任何std::map::~map()析构函数方法,只有一个std::map::~_Tree,这显然不是为了直接使用.所以,在cppreference.com示例代码中,~T()如果T是一个将调用std::map<int,int>什么,以及为我调用具有已知类型的对象的析构函数的正确方法是什么std::aligned_storage?或者我是否使事情变得复杂clear(),这些STL容器中的方法是否保证相当于完全破坏?
或者,有没有更简单的方法呢?因为我可能误解了我的预期用途std::aligned_storage.
听起来你已经读过std::map定义的头文件,并认为它std::map没有析构函数,因为你找不到析构函数的声明.
但是,在C++中,没有声明析构函数的类型将具有编译器隐式声明的析构函数.这个隐式析构函数将调用基数和非静态成员的析构函数.听起来std::map你的库实现是一层薄薄的_Tree.因此,破坏地图需要做的就是破坏树.因此,编译器的默认析构函数可以解决这个问题.
允许->~map()在你的情况下写入,它将调用隐式定义的析构函数,并且地图将被正确销毁.您也可以将此语法与标量类型一起使用,例如int(但由于某些原因,不是数组).