The sizeof()
operator in C gives the size of its operand at compile time. It does not evaluate its operand. For example,
int ar1[10];
sizeof(ar1) // output 40=10*4
sizeof(ar1[-1]) // output 4
int ar2[ sizeof(ar1) ]; // generate an array of 40 ints.
When it came to C++ template class, I find some strange result.
template<typename T>
struct S{
T a;
};
sizeof( S<int> ) // output 4
sizeof( S<bool> ) // output 1
sizeof( vector<int> ) // output 24
sizeof( vector<char> ) // output 24
sizeof( vector<bool> ) // output 40
I guess the sizeof
on vector or other STL container depends on specific environment.
Question 1. How is sizeof
implemented in C/C++? It cannot be a run-time function. Is it a macro? (what I learned in a online tutorial vedio). If it is a Macro, what the #define
of it looks like? When the sizeof()
is executed?
Question 2. If I add a member method void f(){}
to the definition of struct S
. The sizeof(S<int>)
is still 4. Shouldn't the size of the struct increase?
Question 3. STL containers are template classes. Take vector
for example, it has 12 member attributes/types and many member methods? It is easy to explain the output of sizeof( S<int> )
. But I find it hard to explain the output of sizeof( vector<int> )
. Template class should be instantiated at compile-time and the compiler should have total knowledge of the size of the class, i.e. vector<int>
. So should sizeof()
operator know.