0

I am wondering why the sizeof operator on a template of different types returns results I would not expect.

Given

#include <iostream>
#include <string>

template <class T>
class Item {
  public:
    T data;
    int32_t test;
};

template <class T>
class Q {
  public:
    Q(){
        std::cout << sizeof(T) << " ";
        std::cout << sizeof(Item<T>) << " \n";   
    }
};

int main()
{
    Q<int64_t> q1;
    Q<int32_t> q2;
    Q<char> q3;
}

I would expect an output of

8 12
4 8
1 5

But instead

8 16 
4 8 
1 8 

Why?

  • 2
    In a word: padding (usually for alignment purposes). – Jesper Juhl Jun 17 '20 at 19:43
  • 4
    @terratermatwoa Please check your tone. This looks like an _exact_ duplicate to me. In what way is this question different than the linked duplicate? – cdhowie Jun 17 '20 at 19:50
  • 3
    @terratermatwoa Your question *is* pretty much a duplicate of the one it was closed as a duplicate of as far as I can see. You are wondering why you cannot just tally up the size of each member to get the total size of a structure. Which the duplicate answers. – Jesper Juhl Jun 17 '20 at 19:53
  • 4
    The templating is a red herring. There is literally no difference between those three instantiations and three explicitly defined classes. – molbdnilo Jun 17 '20 at 19:53
  • 5
    By the way, it's not mods who pick out duplicate questions, just regular users who have seen these questions asked before. – chris Jun 17 '20 at 19:54
  • 3
    If this is not a duplicate of what you really want to ask, you can re-word the question so that it isn't a duplicate and it'll be re-opened. – user4581301 Jun 17 '20 at 20:01

0 Answers0