分配Union的字段

Nik*_*den 3 c++ setter struct unions

我创建了一个结构使用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;
}
Run Code Online (Sandbox Code Playgroud)

设置值我收到错误(分段错误(核心转储))这样做的正确方法是什么?谢谢!

pad*_*ddy 6

小心.工会中的非POD类型正在寻找麻烦.这样说,这在C++ 11中是受支持的,前提是您最多只能初始化一个成员.这意味着你必须改变工作方式.

琐碎的是,要立即修复您的程序,您只需使用新的展示位置:

void setValue(const std::string& data)
{
    new (&value.str) std::string(data);
}
Run Code Online (Sandbox Code Playgroud)

但是现在,如果您想稍后设置其他成员,则需要在字符串上使用placement delete.要实现这一点,您需要知道有一个字符串可以开始.所以,你不能轻易分开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;
  }
Run Code Online (Sandbox Code Playgroud)

并且不要忘记正确地破坏价值~MyStruct.