Consider the following program:
#include <stdio.h>
struct A
{
int x;
};
int main()
{
printf("%d\n", sizeof(A));
return 0;
}
As expected, this program prints the number 4
because the integer in A
uses 4 bytes. However, let's change the program into this:
#include <stdio.h>
struct A
{
int x;
int& r = x;
};
int main()
{
printf("%d\n", sizeof(A));
return 0;
}
Now the program prints the number 16
.
I've always been told that references in C++ works like an alias, as in offering another name for the same variable. Thus, I expected the struct to still have a size of 4 bytes since the reference r
is just another name for x
, which will get replaced by the actual variable x
when compiled.
Obviusly, this doesn't seem to be the case. Instead, it seems that the reference takes up just as much memory as a pointer would do. If we change int& r = x;
into int* p = &x;
the program will also print 16
. From my point of view this doesn't make any sense because why have references if they take up memory just as pointers do, then we might just use pointers instead.
I did one more test program with the following code:
#include <stdio.h>
struct A
{
int x;
int y;
int z;
int& X = x;
int& Y = y;
int& Z = z;
};
int main()
{
printf("%d\n", sizeof(A));
return 0;
}
And the program above prints 40
. That seems very weird in my eyes since the 3 integers should take up 4 bytes each, making it 12 bytes in total, and leaving 28 bytes left for the references. But 28 is not evenly divisible by 3.
I've compiled this with Visual Studio 2015 in x64 configuration.
So my question is: Have I done something wrong here or why does a C++ reference use up memory in a struct?