There are several questions about lifetime of constant reference on SO, but still I don't get it.
Is this piece of code valid?
struct S
{
const int &ref;
S( const int &x ) : ref(x) { }
};
int main( )
{
S s( 0 );
// ...
use( s.ref );
// ...
return 0;
}
Intuitively I'd say no, since 0
should expire after the expression (S s(0);
) is evaluated.
However both GCC and CLANG compile it fine, without warnings, and valgrind doesn't detect any runtime error.
What am I missing about references?
Seems invalid to me according to 12.2/4 :
There are two contexts in which temporaries are destroyed at a different point than the end of the fullexpression. The first context is when an expression appears as an initializer for a declarator defining an object. In that context, the temporary that holds the result of the expression shall persist until the object’s initialization is complete.
The temporary only gets to live until s
is fully constructed, not until the point where use
is called.