c++ - 分配 Union 的字段

标签 c++ struct setter 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;
}

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);
}

但是现在,如果您以后想设置一个不同 成员,您将需要对字符串使用放置删除。为此,您需要知道从那里开始有一个字符串。因此,您不能轻易地将 setValuesetType 分开。

一个选项(不是特别好)是:

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/

相关文章:

c - 为什么 node* root = malloc(sizeof(int)) 分配 16 个字节的内存而不是 4 个?

python - 为 QUuid 类制作 GDB 调试助手

c - struct 的底层是如何工作的?

C++ 静态初始化 : closest match to Java -Dxxx arguments?

c - C中的二进制文件读/写

java - 在构造函数中从另一个类设置值

java - 封装冗余Setter

c++ - 哪个更合适 : getters and setters or functions?

Android NDK 示例构建错误 linux

c++ - 你如何将项目添加到 QT QListView