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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…