我创建了一个使用 union 作为其字段的结构。这是一个小代码示例:
#include <iostream>
#include <string>
enum Type
{
STR,
INT
};
struct MyStruct
{
Type type;
union Value
{
std::string str;
int i;
Value(){}
~Value(){};
} value;
void setType(Type type)
{
this->type = type;
}
void setValue(const std::string& data)
{
this->value.str = data;
}
MyStruct(){}
~MyStruct(){}
};
int main()
{
MyStruct my;
my.setType(Type::STR);
my.setValue("Hallo");
std::cout << my.value.str << std::endl;
return 0;
}
Setting Value i got an error (Segmentation fault (core dumped)) 正确的方法是什么?谢谢!
最佳答案
小心点。 union 中的非 POD 类型是自找麻烦。也就是说,这在 C++11 中是受支持的,前提是您最多只初始化一个成员。这意味着您必须改变事情的运作方式。
平凡地,要修复你的程序,你只需使用新的放置:
void setValue(const std::string& data)
{
new (&value.str) std::string(data);
}
但是现在,如果您以后想设置一个不同 成员,您将需要对字符串使用放置删除。为此,您需要知道从那里开始有一个字符串。因此,您不能轻易地将 setValue
与 setType
分开。
一个选项(不是特别好)是:
private:
void setType( type ) {
// Destruct existing type
switch( this->type ) {
case STR:
value.str.~std::string();
break;
default:;
}
this->type = type;
}
public:
void setValue( const std::string& data )
{
setType( STR );
new (&value.str) std::string(data);
}
void setValue( int data )
{
setType( INT );
value.i = data;
}
并且不要忘记正确销毁 ~MyStruct
中的值。
关于c++ - 分配 Union 的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640115/