空白基类最优化(empty base optimization, EBO) 详解
本文地址: http://blog.csdn.net/caroline_wendy/article/details/23423247
EBO, empty base optimization, 即空白基类最优化, 可以使派生类节省空间;
但是如果使用复合(composition)的方式, 因为定义了新对象, 所以编译器会进行填充(padding), 填充进一个int, 4位的空间;
代码:
/************************************************* File: test.cpp Copyright: C.L.Wang Author: C.L.Wang Date: 2014-04-11 Description: test Email: morndragon@126.com **************************************************/ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> using namespace std; class Empty {}; class HoldsAnInt { private: int x; Empty e; }; class HoldsAnIntP : private Empty { private: int x; }; int main () { std::cout << "Int : " << sizeof(int) << std::endl; std::cout << "HoldsAnInt(class) : " << sizeof(HoldsAnInt) << std::endl; std::cout << "HoldsAnIntP(inheritance) : " << sizeof(HoldsAnIntP) << std::endl; return 0; }
输出:
Int : 4 HoldsAnInt(class) : 8 HoldsAnIntP(inheritance) : 4
C++ - 空白基类最优化(empty base optimization, EBO) 详解,布布扣,bubuko.com