败犬日报 2025-09-21
败犬日报 2025-09-21
1. [[no_unique_address]]
C++20
允许成员变量和其他成员变量的地址重叠。
cpp
struct Empty {};
struct A {
[[no_unique_address]] Empty e;
int x;
};
这里的 e 的 size 还是 1,只是允许重叠,A 的 size 就可以是 4。[[no_unique_address]]
只是“允许”,不是强制,虽然实际没问题。
什么时候要用到空类成员呢?主要是想要这个空类的行为。往期就讲过 std::unique_ptr
的 Deleter 可以被空基类优化掉,还有 std::vector
的 Allocator。空基类优化是为了 C++17 及之前也能用,有了 no_unique_address 写法上可以直观一点。