0

I have a problem with something like this:

template <typename T1, typename T2>
class X {
  T1 a;
  T2 b;
};

int main() {
 std::cout << sizeof(X<int,char>) << std::endl;
 std::cout << sizeof(X<int,int>) << std::endl;
 std::cout << sizeof(X<char,char>) << std::endl;
};

The output from gcc 4.4.7 is

8
8
2

I do not understand why the first result is 8. For me it should be 6. The same is with double/int template args (gives 16, not 12). I checked also, that this behaviour is independent of whether I use template class or normal class with only 2 members int and char.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
kotu
  • 90
  • 1
  • 8
  • possible duplicate of [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) – TemplateRex Jul 09 '14 at 08:41

1 Answers1

1

That is because of structure alignment. Generally the compiler will try to align objects (by padding) to a particular byte boundary, and both 4-byte and 8-byte boundaries are common.

This page discusses the same idea in C, but it is similar although not exactly the same in C++.

merlin2011
  • 71,677
  • 44
  • 195
  • 329