Brotcrunsher
Brotcrunsher

Reputation: 2254

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

I am currently working on programming a pool allocator. My question boils down to the following code:

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);
}

Is the address of mu always the same as mu2?

Upvotes: 10

Views: 971

Answers (2)

n. m. could be an AI
n. m. could be an AI

Reputation: 120059

It is not enough to ask if two objects have the same address. For instance, an array and its first element are guaranteed to have the same address, but you cannot cast one to the other.

Fortunately, union and its members are guaranteed to be pointer-interconvertible, regardless of whether any of them is standard layout.

Upvotes: 1

user784668
user784668

Reputation:

Yes.

9.2/19 (12.2/24 in N4659):

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.

If the union itself is standard-layout, then the address of the union is the same as its members'.

The addresses of the members are all the same, thanks to 9.5/1 (12.3/2 in N4659):

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.

Upvotes: 19

Related Questions