Last updated:2026-10-12
C++20 [[no_unique_address]]¶
C++那些事: Memory Optimization¶
Memory is often a major concern when a program runs, and reducing memory usage while improving access speed is critical. To address these problems, C++20 introduced the no_unique_address feature, combined with the Empty Base Optimization (EBO), giving developers an effective way to optimize memory layout.
1. Empty Base Optimization (EBO)¶
EBO means that an empty base class (a class with no data members) takes up no extra memory in a derived class. The C++ compiler merges the instances of these empty base classes, avoiding unnecessary memory overhead. This is especially useful when designing complex class hierarchies, as it can effectively reduce object sizes.
#include <iostream>
class Empty {};
class Derived : public Empty {
int value;
public:
Derived(int v) : value(v) {}
};
class Test {
int value;
public:
Test(int v) : value(v) {}
Empty e;
};
int main() {
std::cout << sizeof(Derived) << std::endl;
std::cout << sizeof(Test) << std::endl;
return 0;
}
In the code above, the Derived class occupies only the size of an int in memory, not the size of int plus Empty. This is because the compiler takes advantage of EBO.
So what do you guess the output above is?
2. The no_unique_address Feature¶
C++20 introduced the no_unique_address feature, which lets us explicitly mark certain class members so that they occupy no extra space in memory. It is especially well suited to <0-byte objects>, for example:
In a unique_ptr where the Deleter is an empty struct/class, the resulting sizeof is 16; with C++20 it can take up no bytes, and the whole sizeof becomes 8.
template<class T, class Deleter>
class unique_ptr {
T* pointer = nullptr;
[[no_unique_address]] Deleter deleter;
public:
// 其他成员函数...
};
That's all for this section.
Related Topics¶
- Getting Started with C++20 Coroutines | C++那些事
- C++20 channel in Practice | C++那些事
- C++20 Concepts | C++那些事
- C++20 constexpr and the Comma Expression | C++那些事
- C++20 Byte Order (endian) | C++那些事
- C++20 Lambda Expressions (Part 1) | C++那些事
- C++20 Modules | C++那些事
- C++20 Ranges Library | C++那些事
- C++20 std::span Design and Pitfalls | C++那些事
- A Guide to C++20 New Features | C++那些事