C + +: Blank base class optimization (empty base optimization, EBO) detailed

Source: Internet
Author: User
Tags inheritance

EBO, empty base optimization, which is the optimization of the blank base class, can make the derived class space-saving;

But if you use a composite (composition) method, because the new object is defined, the compiler fills (padding) and fills in an int, 4-bit space;

Code:

/************************************************* 
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;  
}

Output:

Int:4  
Holdsanint (Class): 8  
holdsanintp (inheritance): 4

Author: csdn Blog spike_king

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.