First question on StackOverflow so please be indulgent, and don't hesitate to give me feedback on how i could've asked the coming question better. Thanks !
I was wondering,
I know that reference to stack allocated objects take no memory space and have no overhead at exec time, i.e. :
int x;
x = 0;
and
int x;
int& y = x;
y = 0;
Should be exactly identical when compiled. This sounds obvious to me since the address of b is known at compile time (because it's the same as a, which is known at compile time)
However, i don't know how a C++ compiler handles this if the address is not known at compile time, which happens (as far as i know) when the object being referenced is allocated on the heap, i.e. :
A& x = *new A();
The value of &x in this context has to be stored somewhere in the compiled code, resulting in a different behavior than if you had a reference to an object allocated on the stack, right ?
So, i know the address of a reference to a stack allocated object has to be an r-value (because of my first example), thus one cannot modify it.
But why one cannot modify the address of a reference to a heap allocated object (since it has to be an l-value as far as i understand it, because of not being able to know it at compile time) ? Why do we only have a "reference" type, and not "reference to stack allocated object" + "reference to heap allocated objects" types, since they are obviously not treated the same way in implementation ?
Thanks for your insights !