将结构复制(使用赋值)到并集内部的结构中,从而导致段错误 [英] Copying (using assignment) a structure to a structure inside a union causing seg fault
问题描述
我编写了以下代码:
#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;
}
能否请您解释细分错误的原因?我无法解读回溯跟踪中的数据所暗示的含义.
Can you please explain why the segmentation fault ? I am unable to decipher what that the data in the back trace suggests.
推荐答案
union foo
无法初始化bar对象(它如何知道要调用哪个成员的初始化程序?),因此无法初始化std::string
s .如果要使用foo内的bar,则需要手动对其进行初始化,就像这样...
union foo
can't initialize the bar object (how does it know which member's initializer to call?) and consequently can't initialize the std::string
s. If you want to use the bar inside of foo, then you need to manually initialize it, like so...
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();
或者,您可以尝试将此功能本身引入联合的构造函数和析构函数中.
Alternatively, you can try to roll this functionality into the union's constructors and destructors yourself.
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(); }
请注意,复制也需要特殊处理.
Note that copying also needs special handling.
这篇关于将结构复制(使用赋值)到并集内部的结构中,从而导致段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!