If you allocate an object using new
, it will remain in memory forever - until you delete
it. It's not a temporary object.
a
is a member of A
, and as such part of the allocation.
EDIT: Thanks for the comments. I would say - no, this is not correct. Consider this:
struct A {
const int &a;
A () : a(3) {} // version 1
A (const int &i) : a(i) {} // version 2
};
void foo() {
A *pA;
{
int x;
pA = new A(x);
}
// Now pA->a is pointing to the address where `x` used to be,
// but the compiler may very well put something else in this place now
// because x is out of scope.
}
The answer is more obvious if the lifetime of the A
object spans across several functions.
Side note: I find the word "contents" a bit ambiguous here. Equate the reference with a pointer, so your a
is basically pointing to an integer. const or not, if the integer does no longer exist (because it was on the stack and has been removed), your a
- while still pointing to the same address in memory - is referencing something else now. The GotW article appears to be talking about the compiler prolonging the lifetime of the object being pointed to by the reference. The reference itself, again, is just a pointer.