Namespaces
Variants

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

From cppreference.net
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications ( until C++17* )
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
Attributes
(C++23)
(C++11) (until C++26)
(C++14)
(C++20)
(C++17)
(C++11)
no_unique_address
(C++20)
(C++20)

允许此数据成员与其类的其他非静态数据成员或基类子对象重叠。

目录

语法

[ [ no_unique_address ] ]

说明

适用于在非静态数据成员(非位域)的声明中所声明的名称。

使此成员子对象 可能重叠 ,即允许该成员与其类的其他非静态数据成员或基类子对象重叠。这意味着如果该成员具有空类类型(例如无状态分配器),编译器可以优化其不占用空间,就像它是 空基类 一样。如果该成员非空,其尾部填充空间也可被重用于存储其他数据成员。

注释

[ [ no_unique_address ] ] 在 MSVC 中即使处于 C++20 模式也会被忽略;取而代之的是提供了 [ [ msvc :: no_unique_address ] ]

示例

#include <boost/type_index.hpp>
#include <iostream>
struct Empty {}; // 空类类型对象的尺寸至少为1
static_assert(sizeof(Empty) >= 1);
struct X
{
    int i;
    Empty e; // 至少需要一个额外字节为‘e’提供唯一地址
};
static_assert(sizeof(X) >= sizeof(int) + 1);
struct Y
{
    int i;
    [[no_unique_address]] Empty e; // 空成员被优化掉
};
static_assert(sizeof(Y) >= sizeof(int));
struct Z
{
    char c;
    // e1和e2不能共享相同地址,因为它们的类型相同,即使标记了[[no_unique_address]]
    // 但任意一个都可以与‘c’共享地址
    [[no_unique_address]] Empty e1, e2;
};
static_assert(sizeof(Z) >= 2);
struct W
{
    char c[2];
    // e1和e2不能拥有相同地址,但其中一个可以与c[0]共享,另一个与c[1]共享:
    [[no_unique_address]] Empty e1, e2;
};
static_assert(sizeof(W) >= 2);
template <typename T>
void print_size_of()
{
    using boost::typeindex::type_id;
    std::cout << "sizeof(" << type_id<T>() << ") == " << sizeof(T) << '\n';
}
int main()
{
    print_size_of<Empty>();
    print_size_of<int>();
    print_size_of<X>();
    print_size_of<Y>();
    print_size_of<Z>();
    print_size_of<W>();
}

可能的输出:

sizeof(Empty) == 1
sizeof(int) == 4
sizeof(X) == 8
sizeof(Y) == 4
sizeof(Z) == 2
sizeof(W) == 3

参考文献

  • C++23 标准 (ISO/IEC 14882:2024):
  • 9.12.11 非唯一地址属性 [dcl.attr.nouniqueaddr]
  • C++20 标准 (ISO/IEC 14882:2020):
  • 9.12.10 无唯一地址属性 [dcl.attr.nouniqueaddr]