Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing a struct that contains a string

I just learned about padding, and I was trying to do some tests about it, I tried to pack this struct :

struct B {
        int a,b,c;
        string s;
        char x;
        string t;
        char y;
        string u;

}__attribute__((packed)) ;

But I get this Warning :

warning: ignoring packed attribute because of unpacked non-POD field 'std::string B::u'
      string u;

Does this mean that structs containing strings cannot be packed ? Is there any other way to do it ? if so does it affect the performance ?

like image 719
Othman Benchekroun Avatar asked Oct 20 '22 15:10

Othman Benchekroun


1 Answers

A good rule of thumb is to sort your members from biggest to smallest. That way your data is aligned and (usually) has no gaps. E.g. on VS2013 for an x64 target the following layout requires 112 instead of 128 bytes:

struct B {  
    string s,t,u; 
    int a,b,c;    
    char x,y;
};

For an x86 target however, this only saves you 4 bytes. Whether or not and how this impacts your performance depends on so many other factors, that it can only be determined by measurement.

like image 185
MikeMB Avatar answered Oct 22 '22 22:10

MikeMB