空基优化
即使类型为空 class 类型(即,没有非静态数据成员的 class 或 struct),任何对象或成员子对象的大小必须至少为 1,以便能够保证相同类型的不同对象的地址始终是不同的。
但是,基础 class 子对象不是那么受约束,可以从对象布局中完全优化:
#include <cassert>
struct Base {}; // empty class
struct Derived1 : Base {
int i;
};
int main() {
// the size of any object of empty class type is at least 1
assert(sizeof(Base) == 1);
// empty base optimization applies
assert(sizeof(Derived1) == sizeof(int));
}
空基本优化通常由分配器感知标准库类(std::vector,std::function,std::shared_ptr 等)使用,以避免在分配器无状态时占用其分配器成员的任何额外存储。这是通过存储一个所需的数据成员(例如 begin,end 或 capacity 指针)来实现的。
参考: cppreference