Size of a Reference & How a Reference is Handled

Jul 13, 2011 at 8:35pm
I am concerned by this test that I performed with references:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

class A
{
	short &a;

	A();
public:
	A(short &a) : a(a) {}
	A(A &from) : a(from.a) {}
};

int main()
{
	short x = 7;
	A a (x);
	cout << sizeof(a) << ' ' << sizeof(short&) << endl;
	cin.sync();
	cin.ignore();
}
4 2
As you can see the output is quite different from what it would seem to be. I am wondering how references are dealt with in this case, if it's a special case or what. Does the reference in the class have to be handled differently because it will not always been the same? Would a reference int &X = x; be resolved at compile time and not at run time? I understand references perfectly, I just am not sure about how they are generally handled.
Jul 13, 2011 at 9:13pm
References aren't objects, so sizeof(T&) is always equal to sizeof(T).
However, since references are almost universally implemented using pointers, they'll still take up space (sizeof(short*), to be precise) when being part of a structure. That's how it is in practice, but the standard gives you no guarantee on that.
Jul 13, 2011 at 10:50pm
Would a reference int &X = x; be resolved at compile time?
I am 99.9% certain they are resolved at compile time, using pointers as Athar explained.
No I am not: I just understood I don't understand what does it mean to resolve a reference at compile time.
Last edited on Jul 13, 2011 at 10:58pm
Jul 13, 2011 at 11:24pm
References are actually a fairly complex subject, requiring some special magic under the hood. Don't assume they are always a simple pointer.

There are other issues that may be involved in your test as well, such as automatic padding in the structure and any possible overhead your compiler adds to the class structure to make things go nicely.

Hope this helps.
Topic archived. No new replies allowed.