[SOLVED] Is it implementation-defined that how to deal with [[no_unique_address]]?

Issue

Below is excerpted from cppref but reduced to demo:

#include <iostream>
 
struct Empty {}; // empty class

struct W
{
    char c[2];
    [[no_unique_address]] Empty e1, e2;
};
 
int main()
{ 
    std::cout << std::boolalpha;

    // e1 and e2 cannot have the same address, but one of them can share with
    // c[0] and the other with c[1]
    std::cout << "sizeof(W) == 2 is " << (sizeof(W) == 2) << '\n';
}

The documentation says the output might be:

sizeof(W) == 2 is true

However, both gcc and clang output as follows:

sizeof(W) == 2 is false

Is it implementation-defined that how to deal with [[no_unique_address]]?

Solution

See [intro.object]/8:

An object has nonzero size if … Otherwise, if the object is a base class subobject of a standard-layout class type with no non-static data members, it has zero size.
Otherwise, the circumstances under which the object has zero size are implementation-defined.

Empty base class optimization became mandatory for standard-layout classes in C++11 (see here for discussion). Empty member optimization is never mandatory. It is implementation-defined, as you suspected.

Answered By – Brian Bi

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *