Copying (using assignment) a structure to a structure inside a union causing seg fault

后端 未结 3 876
醉酒成梦
醉酒成梦 2020-12-22 03:22

I wrote the following code:

#include 
#include 
#include 

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


        
3条回答
  •  情书的邮戳
    2020-12-22 03:42

    You can't use memcpy to copy objects or structure containing objects because they will not be properly initialized. Strings have pointers to char arrays, and if two strings can share the same pointer, there must be some kind of garbage collection (typically a reference counter). If you do f1.b1 = b2, the compiler will generate the code to initialize the strings correctly.

提交回复
热议问题