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

后端 未结 3 875
醉酒成梦
醉酒成梦 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 04:03

    std::string has a non-trivial constructor, that initializes its internal members. Therefore, your struct bar is no POD structure.

    Unions only support POD (this is relaxed in C++11). The compiler cannot decide which constructor of which of the union's members to call. Imagine following situation:

    unition MyUnion {
      std::string s;
      std::vector v;
    };
    

    Should it use vector's or string's constructor to initialize the object?

    So in your situation, when you assign the string to the union's string, the internal data is not initalized, which causes random errors.

提交回复
热议问题