C++에서 class나 struct는 멤버를 하나도 가지지 않아도 크기가 0이 아니라 최소 1은 되어야 한다. 이것은 두 다른 객체가 항상 다른 주소를 갖도록 하기 위해서이다. 그런데 base class의 경우에는 0이 될 수 있다. 이것을 Empty base optimization이라고 한다. unique_ptr가 오버헤드가 전혀 없는 것도 이것 때문이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#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)); } |
그런데 base class가 non-static 멤버이거나 non-static 멤버의 base 이면 EBO가 적용되지 않는다. 왜냐하면 두 base subobject가 다른 주소를 가져야 하기 때문이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <cassert> struct Base {}; // empty class struct Derived1 : Base { int i; }; struct Derived2 : Base { Base c; // Base, occupies 1 byte, followed by padding for i int i; }; struct Derived3 : Base { Derived1 c; // derived from Base, occupies sizeof(int) bytes int i; }; int main() { // empty base optimization does not apply, // base occupies 1 byte, Base member occupies 1 byte // followed by 2 bytes of padding to satisfy int alignment requirements assert(sizeof(Derived2) == 2*sizeof(int)); // empty base optimization does not apply, // base takes up at least 1 byte plus the padding // to satisfy alignment requirement of the first member (whose // alignment is the same as int) assert(sizeof(Derived3) == 3*sizeof(int)); } |