Although sizeof(ref_var)
returns the size of the referenced object, space is still required to store a reference in a structure, for instance, and in common implementations the space allocated to store a reference is the same as the space allocated to store a pointer. That may not be required by the standard, but this code at least shows the effect:
#include <iostream>
using namespace std;
char c1 = 'a';
char &c2 = c1;
struct x
{
char c1;
char c2;
char c3;
char c4;
int i4a;
char &r1;
int i4b;
int i4c;
x() : r1(c1) { }
};
struct y
{
char c1;
char c2;
char c3;
char c4;
int i4a;
int i4b;
int i4c;
};
int main()
{
cout << sizeof(c2) << endl;
cout << sizeof(y) << endl;
cout << sizeof(x) << endl;
return 0;
}
I make no pretense that it is 'great code' - it isn't - but it demonstrates a point. Compiled on MacOS X 10.6.4 with the C++ compiler from the GNU Compiler Collection (GCC 4.5.1) in default (64-bit) mode, the output is:
1
16
24
When compiled in 32-bit mode, the output is:
1
16
20
The first line of output demonstrates that 'sizeof(ref_var)
' does indeed return the size of the referenced object. The second line shows that a structure with no reference in it has a size of 16 bytes. The third line shows that a very similar structure with a reference embedded in it at an 8-byte boundary (on a system where sizeof(int) == 4
) is 8 bytes larger than the simpler structure under a 64-bit compilation and 4 bytes larger under a 32-bit compilation. By inference, the reference part of the structure occupies more than 4 bytes and not more than 8 bytes under the 64-bit compilation, and occupies not more than 4 bytes under the 32-bit compilation. This suggests that (in at least one popular implementation of C++) that a reference in a structure occupies the same amount of space as a pointer - as asserted in some of the other answers.
So, it may be implementation dependent, but the comment that a reference occupies the same space as a pointer holds true in at least one (rather widely used) implementation.