Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why reference variable inside class always taking 4 bytes irrespect of type? (on 32-bit system)

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 ?

like image 638
bjskishore123 Avatar asked Oct 14 '10 07:10

bjskishore123


1 Answers

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.

like image 163
Alexander Rafferty Avatar answered Oct 06 '22 18:10

Alexander Rafferty