W3cubDocs

/C++

C++ attribute: no_unique_address (since C++20)

Indicates that this data member need not have an address distinct from all other non-static data members of its class.

Syntax

[[no_unique_address]]

Explanation

Applies to the name being declared in the declaration of a non­-static data member that's not a bit field.

Indicates that this data member need not have an address distinct from all other non-static data members of its class. This means that if the member has an empty type (e.g. stateless Allocator), the compiler may optimise it to occupy no space, just like if it were an empty base.

Example

struct Empty {}; // empty class
 
struct X {
    int i;
    Empty e;
};
 
struct Y {
    int i;
    [[no_unique_address]] Empty e;
};
 
int main()
{
    // the size of any object of empty class type is at least 1
    static_assert(sizeof(Empty) >= 1);
 
    // at least one more byte is needed to give e a unique address
    static_assert(sizeof(X) >= sizeof(int) + 1);
 
    // empty member optimized out
    static_assert(sizeof(Y) == sizeof(int));
}

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/language/attributes/no_unique_address