kotu
kotu

Reputation: 90

The size of the template class

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.

Upvotes: 0

Views: 808

Answers (1)

merlin2011
merlin2011

Reputation: 75565

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++.

Upvotes: 1

Related Questions