I was suprised recently to find a temporary variable in C++ being promoted to having full lexical scope:
class Foo {
public:
Foo() {
std::cout << "A";
}
~Foo() {
std::cout << "B";
}
};
int main(void)
{
// Prints "ACB", showing the temporary being promoted to having lexical scope.
const Foo& f = Foo();
std::cout << "C";
return 0;
}
Aside from the dubious behavior of assigning a temporary to a reference, this actually works just fine (tested in VS2010 and G++ v4.1). The output is ACB, showing clearly that the temporary object has been promoted to having lexical scope, and is only destructed at the end of the function (B is printed after C).
Other temporary variables don't behave this way:
int main(void)
{
// Prints "ACBD", showing that the temporary is destroyed before the next sequence point.
const int f = ((Foo(), std::cout << "C"), 5);
std::cout << "D";
return 0;
}
As per my code comment this prints ACBD, showing that the temporary variable is kept until the entire expression has finished evaluating (why C is printed before B), but still destroyed before the next sequence point (why B is printed before D). (This behaviour was how I thought all temporary variables in C++ worked. I was very surprised at the earlier behaviour.)
Can someone explain when it is legal for a temporary to be promoted to have lexical scope like this?