This outputs F~
but I was expecting ~F
#include <iostream>
struct Foo {
int _x;
operator const int & () const {return _x;}
~ Foo () {std :: cout << "~";}
};
void foo (const int &)
{
std :: cout << "F";
}
int main ()
{
foo (Foo ());
}
I constructed this as a counterexample to show that the most-important-const is an exception rather than a rule. It is normally written as
when a const reference binds to a temporary, then the lifetime of that temporary is extended to the lifetime of the reference
I was trying to illustrate that, although Foo()
is a temporary, the reference to _x
returned by the conversion operator is not, and that the above code is unsafe.
But the output seems to prove that the example is safe, the lifetime of the temporary Foo()
is extended by the existence of a const reference to one of its members.
Is this right? Where in the standard is this specified?