【发布时间】:2014-05-10 21:18:02
【问题描述】:
我写了以下代码:
#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;
}
你能解释一下为什么会出现分段错误吗?我无法解读回溯中的数据所暗示的内容。
【问题讨论】:
-
@Wilding:代码无法编译。
-
是的。请再检查一次。我是这样编译的:
g++ -Wall -g -std=c++11 un.cpp -o u -
我在VS2013上编译过。
-
你能粘贴错误吗?
-
错误 2 错误 C2039: 'b1' : 不是 'foo' main.cpp 的成员 41 1 错误 3 错误 C2039: 'b1' : 不是 'foo' main.cpp 的成员43 1 错误 4 错误 C2228:'.s3' 左侧必须有类/结构/联合 main.cpp 43 1 错误 5 错误 C2228:'.s4' 左侧必须有类/结构/联合 main.cpp 43 1跨度>