C++ templates

Please consider the snippet below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include<iostream>
using namespace 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?
Unused space called "padding" is inserted between class members in order to preserve their alignment requirements.

Google "structure padding and alignment" without the quotes.

pahole(1) can be used to visualize structure layouts:
https://godbolt.org/z/913rYv
Last edited on
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>
using namespace 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;
}


10                        
13                      

Last edited on
@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.

There was a discussion about this just a few days ago:
http://www.cplusplus.com/forum/general/272055/
Last edited on
Topic archived. No new replies allowed.