C++:抽象联合和新放置运算符的行为?

C++: Behavior of abstract union and new placement operator?

据我了解,union 的大小是该联盟中最大成员的大小。有谁知道在向其添加非固定大小的容器(例如 string 时联合会如何表现?尺寸是多少?另外,使用新的放置操作时,大小如何变化?谢谢!

这是一个例子:

#include <string>
using namespace std;

class X {
public:
    union {
        int i;
        string s;
    };
    X(string ss) { new(&s) string{ss}; };
    ~X() { s.~string(); };
};

int main(int argc, char *argv[])
{
    X xx{"abc"};

    return 0;
}

sizeof(std::string) 始终相同,无论字符串为空还是包含字符串。需要新放置运算符的唯一原因是联合中存在字符串,因为存储在字符串和整数之间共享。

It's my understanding a union's size is that of largest member on that union.

不完全是。如果一个成员有更严格的对齐要求,而另一个成员更大,但不是上述对齐的倍数,那么联合的总大小可能比任何一个成员都大。

Does anyone know how a union behaves when a non fixed size container

C++ 中没有非固定大小的类型。所有类型都有一个编译时常量大小。动态容器从空闲存储区分配内存,并使用常量指针间接引用该内存。

What is the size?

恰好是 sizeof(X) 个字节。

Also, how does the size change when the new placement operation is used?

不变。