Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading