c++ - 将结构复制(使用赋值)到 union 内的结构导致段错误

标签 c++ struct memcpy unions

我写了下面的代码:

#include <iostream>
#include <string>
#include <cstring>

struct bar
{
  std::string s3;
  std::string s4;
}Bar;

union foo
{
  char * s1;
  char * s2;
  bar    b1;

  foo(){};
  ~foo(){};
}Foo;


int main ()
{
  foo f1;
  bar b2;

  std::string temp("s3");
  b2.s3 = temp;
  b2.s4 = temp;

  //f1.b1 = b2;                           //-- This Fails (Seg faults)

  /*
    #0  0x00002b9fede74d25 in std::string::_Rep::_M_dispose(std::allocator<char> const&) [clone .part.12] ()
        from /usr/local/lib64/libstdc++.so.6
    #1  0x00002b9fede75f09 in std::string::assign(std::string const&) () from /usr/local/lib64/libstdc++.so.6
    #2  0x0000000000400ed1 in bar::operator= (this=0x7fff3f20ece0) at un.cpp:5
    #3  0x0000000000400cdb in main () at un.cpp:31
  */

  memcpy( &f1.b1, &b2, sizeof(b2) );  //-- This Works 

  std::cout << f1.b1.s3 << " " << f1.b1.s4 << std::endl;
  return 0;
} 

你能解释一下为什么会出现段错误吗?我无法破译回溯中的数据所暗示的内容。

最佳答案

union foo 无法初始化 bar 对象(它如何知道要调用哪个成员的初始化程序?)因此无法初始化 std::string .如果你想使用foo里面的bar,那么你需要手动初始化它,像这样......

new (&f1.b1) bar; // Placement new
f1.b1 = b2;
// And later in code you'll have to manually destruct the bar, because
//   foo doesn't know to destruct the bar either...
f1.b1.~bar();

或者,您可以尝试自己将此功能添加到 union 的构造函数和析构函数中。

foo() : b1() {}
// Or you construct like this, which you might need to for a non-trivial union...
// foo() { new (&b1) bar; }  // Placement new.
~foo() { b1.~bar(); }

注意复制也需要特殊处理。

关于c++ - 将结构复制(使用赋值)到 union 内的结构导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763191/

相关文章:

c++ - Qt 上的 PRECOMPILED_HEADER 和 Subdirs 模板

c++ - 您可以指定线程终止的顺序,即线程依赖性吗?

c++ - 使用 SFINAE 进行结构定义

c++ - 没有 make.exe 的 mingw 64 发货?

c++ - c++中的atof、结构和指针

c++ - 使用 memcpy 函数复制 char 数组 C++

c - 通过将结构体的地址获取到其他类型的结构体的指针来获取临时[-fpermissive]的地址

c++ - 如何在C++中将结构传递给函数

c++ - 结构的一部分的 memcpy

C++ memcpy函数,为什么用*s++而不是s[i]