C++17 标准是否保证联合的地址与其成员的地址相同?

Does the C++17 standard guarantee that the address of a union is the same as the address of its members?

我目前正在编写池分配器的程序。我的问题归结为以下代码:

template <typename T>
union myUnion {
    T data;
    myUnion<T>* nextUnion;
};

void someFunction(){
    myUnion<T> mu;
    T* t = new (std::addressof(mu.data)) T();
    //some code
    myUnion<T>* mu2 = reinterpret_cast<myUnion<T>*>(t);
}

mu的地址总是和mu2一样吗?

是。

9.2/19(N4659 中为 12.2/24):

If a standard-layout class object has any non-static data members, its address is the same as the address of its first non-static data member.

如果工会本身是标准布局,那么工会的地址与其成员的地址相同。

感谢9.5/1(N4659为12.3/2),会员地址都一样:

Each non-static data member is allocated as if it were the sole member of a struct. All non-static data members of a union object have the same address.

仅仅询问两个对象是否具有相同的地址是不够的。例如,数组及其第一个元素保证具有相同的地址,but you cannot cast one to the other.

幸运的是,union 及其成员保证是 pointer-interconvertible,不管它们是否是标准布局。