What is the size of ( variable = &anotherVar )
int y = 10; // the size of y is 4 bytes
int & x = y; // what is the size of x that receives the address of y
What is the size of ( variable = &anotherVar )
int y = 10; // the size of y is 4 bytes
int & x = y; // what is the size of x that receives the address of y
It is unspecified whether or not a reference requires storage (C++11 8.3.2.4)
For the case
int y = 10;
int & x = y;
the compiler may not use any extra memory; it will just consider x
to be an alias of y
. Once x
is initialized it can't be reassigned to reference another variable, so the compiler can do this.
If a reference is used as a function parameter or in a class/struct, then it will probably be implemented internally as a pointer so the size will be sizeof(int*)
. Of course, if a function with reference parameters is inlined, then no extra memory will be needed.
Assuming you're talking about the physical size of the reference type int&
, it will almost certainly be the same size as the pointer type int*
, which is typically 4 or 8 bytes on modern architectures (32- or 64-bit processors).
If you want to measure it on your compiler, use this:
struct Test { int& x; }
printf("%d\n", (int)sizeof(Test));
Also note that, technically, your compiler might pad the Test
struct and give you the wrong answer, but this will probably work fine.
Note that sizeof(int&)
is the same as sizeof(int)
, and doesn't tell you exactly how much space an int&
will use if it is a data member.
The result of application of sizeof to a reference or a reference type is the size of the referenced type. (C++ 03, 5.3.3.2)
If your int is 4 bytes (it does not have to be), then so is the reference.
So I think you are confusing pointers and references.
You ask what is (x = &y) ?
But then your example is a reference (X& x = y).
I think you mean what is the size of a pointer? It is architecture dependent. To find out what it is on your paticular target type:
cout << sizeof(void*)
A simple test should clear up any confusion:
#include <iostream>
using namespace std;
void f(char &r)
{
cout << sizeof(r) << endl;
cout << sizeof(&r) << endl;
}
int main()
{
char x = 0;
char &y = x;
cout << sizeof(y) << endl;
cout << sizeof(&y) << endl;
f(x);
return 0;
}
Output (compiled as an x86 32-bit program):
1
4
1
4