#include<iostream>
usingnamespace std;
template<class T, class U, class V=double>
class A{
T x;
U y;
V z;
};
int main(){
A<char,char> a;
A<int,char> b;
cout<<sizeof(a)<<endl;
cout<<sizeof(b)<<endl;
}
The output to the above program is "16 16".
Now an integer variable is of 4 bytes, double is of 8 and char is 1. So I expect the output to be "10 13". Could someone please explain what's going on behind the scenes here?
As mbozzi stated, this is because of padding added for alignment. You can force it to not do this with compiler-specific attributes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
usingnamespace std;
template<class T, class U, class V=double>
class [[gnu::packed]] A{
T x;
U y;
V z;
};
int main(){
A<char,char> a;
A<int,char> b;
cout<<sizeof(a)<<endl;
cout<<sizeof(b)<<endl;
}
@mbozzi @TheToaster Thanks for your help, I now have a basic idea what the compiler does. This padding is required for faster memory access - something to do with the word size and least amount of iterations to get the same data if I'm not wrong?
In general, objects of a particular type must be aligned - placed in storage at an address that is a multiple of a particular power of two. This power of two is called the type's alignment requirement.
The padding space ensures that each of A's member subobjects are properly aligned. Aligning data is not necessarily optional, i.e., on some systems if data is misaligned it can't be accessed at all, and attempts to access it anyway will cause an exception in hardware.