views:

63

answers:

2

Hi, I have below code, running on 32-bit windows, visual-studio.

template <class T>
class Test
{
public:
 T &ref;
 Test(T &x)
  :ref(x)
 {}
};

int main()
{
 cout<<"sizeof Test<int> : "<<sizeof(Test<int>)<<endl;
 cout<<"sizeof Test<double> : "<<sizeof(Test<double>)<<endl;
 cout<<"sizeof Test<char> : "<<sizeof(Test<char>)<<endl;
}

Output is:

sizeof Test<int> : 4
sizeof Test<double> : 4
sizeof Test<char> : 4

Compiler giving 4 bytes for reference variable inside class irrespect of the type of reference. Variable value can not be stored in those 4 bytes.

What information compiler will store in those 4 bytes ?

is it internally storing the address of referent? so that reference and referent both can write to the same location to be in sync with each other.

Or is it storing name of referent in symbol table ?

+7  A: 

Those for bytes are the reference. A reference is just a pointer internally, and pointers typically use 4 bytes on a 32bit system, irrespective of the data types because it is just an address, not the value itself.

Alexander Rafferty
That's right. The OP might try changing to 64-bit to see the difference.
Daniel Lidström
+3  A: 

Why reference variable inside class always taking 4 bytes irrespect of type?

It isn't!

C++03 5.3.3

When applied to a reference or a reference type, the result is the size of the referenced type.

Also 8.3.2 says

It is unspecified whether or not a reference requires storage.

Prasoon Saurav
@Saurav: I am checking size of object. sizeof reference variable alone comes same as the referent size.
bjskishore123
@bjskishore123 : Your assumption that `reference variable inside class always taking 4 bytes irrespect of type` is incorrect although references are implemented as pointers. Rest `3` bytes in case of `Test<char>` are compiler inserted [padding bytes](http://en.wikipedia.org/wiki/Data_structure_alignment).
Prasoon Saurav
@Saurav: Even when i use double, it is showing 4 bytes only as the size of object. Thats the confusion. Pls check my output in question.
bjskishore123
@bjskishore : because 4 bytes are enough to refer to a type as references are internally implented as pointers. However sizeof the reference itself depends on the referenced type.
Prasoon Saurav
It is not padding. The reference is taking four bytes because it is a pointer, which is an address to a value in memory, not the value itself.
Alexander Rafferty
@Alexander Rafferty : Nopes it is not. See `section 5.3.3` (sizeof).
Prasoon Saurav
@Alexander : Also it is unspecified whether or not a reference requires storage.
Prasoon Saurav
Sizeof() returns the size of the thing it points to.
Alexander Rafferty
Doug