我试图制作一个可以容纳string和int的向量.
error: use of deleted function ‘my_union::~my_union()’
我究竟做错了什么?
#include <iostream> #include <vector> using namespace std; union my_union { string str; int a; }; int main() { vector<my_union> v; my_union u; // error: use of deleted function 'my_union::~my_union()' u.str = "foo"; v.push_back(u); return 0; }
解决方法
从
here
If a union contains a non-static data member with a non-trivial special member function (default constructor,copy/move constructor,copy/move assignment,or destructor),that function is deleted by default in the union and needs to be defined explicitly by the programmer.
您必须显式地定义一个用于联合的析构函数来替换字符串自动删除的析构函数.
另请注意,这仅在c 11中有效.在早期版本中,根本不能在一个联合中使用非平凡特殊成员函数的类型.
从实践的角度来看,这可能还不是一个好主意.