dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: All
May 8, 2000

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Optimizing Member Alignment

A class's size can change simply by playing with the order of its members' declaration. For example:

 
struct A
{
 bool a;
 int b;
 bool c;
}; // sizeof (A) == 12

On my machine, sizeof (A) equals 12. This result might seem surprising because the total size of A's members is only 6 bytes: 1+4+1 bytes. Where did the remaining six bytes come from? The compiler inserted three padding bytes after each bool member to make it align on a word boundary. You can reduce A's size by reorganizing its data members as follows:

 
struct B
{
 bool a;
 bool c;
 int b;
}; // sizeof (B) == 8

This time, the compiler inserted only two padding bytes after the member c. Because b occupies four bytes, it naturally aligns on a word boundary without necessitating additional padding bytes.

As a rule, if your class has several data members of various types, declare the members that occupy a small size (less than the size of an int) successively.

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date