Consider the following code dealing with const references:
const int & func (const int &x)
{
return x;
}
struct Foo {
Foo (const int &x)
: m_x(x) {}
const int & getX ()
{ return m_x; }
const int &m_x;
};
I’d like to know which, if any, of the following is now allowed:
int x = func(int(7));
int y = Foo(int(7)).getX();
Is there any guarantee that the temporary int object still exists before it is used by the assignment or getX?.
UPDATE: So it appears this is safe – but why exactly?
- Is it because temporaries bind to const references recursively and are guaranteed to exist as long as of those bound references to them exists?
- Or is it because they are guaranteed to exist for the duration of the full expression?
Consider the edge case which stores a pointer instead of a reference:
struct Foo {
Foo (const int &x)
: m_x(&x) {}
const int & getX ()
{ return *m_x; }
const int *m_x;
};
int y = Foo(int(7)).getX();
It seems that if case 1) was correct, this would not work. But if case 2) was correct, it would.
Both are safe, because you copy the values into
xandy. The temporaries are valid until the end of the full expression.12.2 Temporary objects