[[no_unique_address]] 属性 ​

什么是 [[no_unique_address]] ​

[[no_unique_address]] 是 C++20 引入的属性,应用于非静态数据成员。它告诉编译器:如果这个成员的类型是空类(没有非静态数据成员),编译器可以让它不占用任何空间,与其他成员共享地址。

C++ 规定每个对象至少占 1 字节,即使是空类也不例外。这导致一个空的成员变量(比如无状态的分配器、删除器、比较器)白白浪费空间。以前解决这个问题需要用空基类优化(EBO),通过继承来消除开销,代码不太直观。[[no_unique_address]] 让你直接用成员变量的方式写,编译器自动优化掉空成员的空间。

cpp
struct Empty {};

struct WithoutAttr {
    int value;
    Empty e;  // 至少占 1 字节 + 对齐填充
};
// sizeof(WithoutAttr) 通常是 8(int 4 + Empty 1 + 3填充)

struct WithAttr {
    int value;
    [[no_unique_address]] Empty e;  // 可以占 0 字节
};
// sizeof(WithAttr) 通常是 4(和 int 一样大)

基本示例 ​

cpp
#include <iostream>
#include <memory>
#include <functional>
#include <type_traits>

// ============================
// 示例1:空类的大小优化
// ============================

struct Empty {};

struct A {
    int x;
    Empty e;  // 没有属性:e 占至少 1 字节
};

struct B {
    int x;
    [[no_unique_address]] Empty e;  // 有属性:e 可以占 0 字节
};

void size_demo() {
    std::cout << "sizeof(Empty) = " << sizeof(Empty) << std::endl;  // 1
    std::cout << "sizeof(int) = " << sizeof(int) << std::endl;      // 4
    std::cout << "sizeof(A) = " << sizeof(A) << std::endl;          // 8(有填充)
    std::cout << "sizeof(B) = " << sizeof(B) << std::endl;          // 4(无开销)
}

// ============================
// 示例2:两个不同空类型的成员
// ============================

struct Tag1 {};
struct Tag2 {};

struct TwoEmpty {
    int value;
    [[no_unique_address]] Tag1 t1;  // 可以和 value 共享地址
    [[no_unique_address]] Tag2 t2;  // 可以和 value 共享地址(类型不同)
};

void two_empty_demo() {
    // t1 和 t2 是不同类型,可以共享同一地址
    std::cout << "sizeof(TwoEmpty) = " << sizeof(TwoEmpty) << std::endl;  // 4

    TwoEmpty te{42};
    // 不同类型的空成员可以有相同地址
    std::cout << "value 地址: " << &te.value << std::endl;
    std::cout << "t1 地址: " << &te.t1 << std::endl;
    std::cout << "t2 地址: " << &te.t2 << std::endl;
}

// ============================
// 示例3:相同空类型不能共享地址
// ============================

struct SameTypeEmpty {
    int value;
    [[no_unique_address]] Empty e1;
    [[no_unique_address]] Empty e2;
    // e1 和 e2 是相同类型,C++ 要求同类型的不同对象有不同地址
    // 所以至少一个要占空间
};

void same_type_demo() {
    std::cout << "sizeof(SameTypeEmpty) = " << sizeof(SameTypeEmpty) << std::endl;
    // 通常是 8,因为 e1 和 e2 不能共享地址

    SameTypeEmpty st{42};
    std::cout << "e1 地址: " << &st.e1 << std::endl;
    std::cout << "e2 地址: " << &st.e2 << std::endl;
    // 地址不同
}

// ============================
// 示例4:无状态分配器优化
// ============================

template<typename T>
struct StatelessAllocator {
    using value_type = T;
    T* allocate(std::size_t n) {
        return static_cast<T*>(::operator new(n * sizeof(T)));
    }
    void deallocate(T* p, std::size_t) {
        ::operator delete(p);
    }
};

// 没有优化的容器节点
template<typename T, typename Alloc>
struct NodeBad {
    T data;
    Alloc alloc;  // 空分配器也占至少 1 字节
};

// 使用 [[no_unique_address]] 优化的容器节点
template<typename T, typename Alloc>
struct NodeGood {
    T data;
    [[no_unique_address]] Alloc alloc;  // 空分配器占 0 字节
};

void allocator_demo() {
    using BadNode = NodeBad<int, StatelessAllocator<int>>;
    using GoodNode = NodeGood<int, StatelessAllocator<int>>;

    std::cout << "无优化节点: " << sizeof(BadNode) << " 字节" << std::endl;   // 8
    std::cout << "优化后节点: " << sizeof(GoodNode) << " 字节" << std::endl;  // 4
}

// ============================
// 示例5:compressed_pair 实现
// ============================

// C++20 之前用 EBO(空基类优化)实现
template<typename T1, typename T2>
struct CompressedPairOld : private T2 {  // 继承空类实现 EBO
    T1 first;
    T2& second() { return *this; }
};

// C++20 用 [[no_unique_address]] 实现——简洁得多
template<typename T1, typename T2>
struct CompressedPair {
    [[no_unique_address]] T1 first;
    [[no_unique_address]] T2 second;
};

void compressed_pair_demo() {
    CompressedPair<int, Empty> pair{42, {}};

    std::cout << "CompressedPair<int, Empty> 大小: "
              << sizeof(pair) << std::endl;  // 4

    CompressedPair<int, int> pair2{1, 2};
    std::cout << "CompressedPair<int, int> 大小: "
              << sizeof(pair2) << std::endl;  // 8(两个 int 不能压缩)
}

// ============================
// 示例6:无状态删除器(类似 unique_ptr)
// ============================

template<typename T, typename Deleter = std::default_delete<T>>
class SmartPtr {
    T* ptr_;
    [[no_unique_address]] Deleter deleter_;

public:
    explicit SmartPtr(T* p, Deleter d = Deleter{})
        : ptr_(p), deleter_(d) {}

    ~SmartPtr() {
        if (ptr_) deleter_(ptr_);
    }

    T& operator*() const { return *ptr_; }
    T* operator->() const { return ptr_; }

    SmartPtr(const SmartPtr&) = delete;
    SmartPtr& operator=(const SmartPtr&) = delete;
};

void smart_ptr_demo() {
    // 无状态删除器——SmartPtr 大小等于一个指针
    SmartPtr<int> p1(new int(42));
    std::cout << "SmartPtr<int> 大小: " << sizeof(p1) << std::endl;
    std::cout << "  *p1 = " << *p1 << std::endl;

    // 有状态删除器——大小增加
    auto custom_deleter = [](int* p) {
        std::cout << "  自定义删除: " << *p << std::endl;
        delete p;
    };
    SmartPtr<int, decltype(custom_deleter)> p2(new int(100), custom_deleter);
    std::cout << "SmartPtr<int, lambda> 大小: " << sizeof(p2) << std::endl;
}

// ============================
// 示例7:哈希表中的比较器和哈希函数
// ============================

template<typename Key, typename Value,
         typename Hash = std::hash<Key>,
         typename Pred = std::equal_to<Key>>
class SimpleHashMap {
    [[no_unique_address]] Hash hasher_;
    [[no_unique_address]] Pred pred_;
    // 真实数据结构省略...
    int dummy_data_ = 0;

public:
    std::size_t hash(const Key& k) const { return hasher_(k); }
    bool equal(const Key& a, const Key& b) const { return pred_(a, b); }
};

void hashmap_demo() {
    SimpleHashMap<int, int> map;
    std::cout << "SimpleHashMap 大小: " << sizeof(map) << std::endl;
    // Hash 和 Pred 都是空类,不占空间

    std::cout << "hash(42) = " << map.hash(42) << std::endl;
    std::cout << "equal(1, 1) = " << std::boolalpha
              << map.equal(1, 1) << std::endl;
}

int main() {
    std::cout << "=== 大小优化 ===" << std::endl;
    size_demo();

    std::cout << "\n=== 两个空类型 ===" << std::endl;
    two_empty_demo();

    std::cout << "\n=== 相同类型 ===" << std::endl;
    same_type_demo();

    std::cout << "\n=== 分配器 ===" << std::endl;
    allocator_demo();

    std::cout << "\n=== compressed_pair ===" << std::endl;
    compressed_pair_demo();

    std::cout << "\n=== 智能指针 ===" << std::endl;
    smart_ptr_demo();

    std::cout << "\n=== 哈希表 ===" << std::endl;
    hashmap_demo();

    return 0;
}

[[no_unique_address]] vs 空基类优化(EBO) ​

特性[[no_unique_address]]EBO(空基类优化)
实现方式属性标注成员继承空基类
代码复杂度简单复杂(需要模板特化)
多个空成员直接标注多个需要多重继承
非空类型时自动退化为普通成员需要特化处理
可读性好差

适用场景 ​

  • 无状态分配器作为成员变量
  • 无状态删除器(类似 unique_ptr 的实现)
  • 无状态比较器、哈希函数
  • 策略模式中的空策略类
  • 任何模板类中可能为空类的成员

常见问题 ​

MSVC 支持 [[no_unique_address]] 吗?

MSVC 有一个已知问题:它在 C++20 模式下会忽略标准的 [[no_unique_address]]。需要使用 MSVC 特有的 [[msvc::no_unique_address]]。可以用宏来兼容:

cpp
#ifdef _MSC_VER
#define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
#else
#define NO_UNIQUE_ADDRESS [[no_unique_address]]
#endif

两个相同类型的空成员能共享地址吗?

不能。C++ 要求同类型的不同对象有不同地址。如果两个 [[no_unique_address]] 成员是相同类型的空类,编译器必须给它们分配不同地址。

非空类型加 [[no_unique_address]] 有效果吗?

对于非空类型,这个属性允许编译器重用成员的尾部填充(tail padding)来存储其他成员。但一般来说,非空类型不会有明显的大小变化。

注意事项 ​

  • 只能用于非静态数据成员
  • 相同类型的不同成员不能共享地址
  • MSVC 需要使用 [[msvc::no_unique_address]]
  • 非空类型上使用效果有限
  • 主要用于模板类中可能为空的策略/分配器/删除器成员

总结 ​

[[no_unique_address]] 是 C++20 引入的属性,允许空类型的数据成员不占用额外空间。它替代了以前复杂的空基类优化(EBO)技术,只需在成员声明前加上属性标注就行。对于标准库的实现(如容器中的分配器、unique_ptr 中的删除器、哈希表中的比较器)来说,这个属性可以在成员为空类时消除空间浪费,同时在成员非空时自动退化为普通成员。注意 MSVC 需要使用 [[msvc::no_unique_address]] 替代。