I know that a temporary cannot be bound to a non-const reference, but it can be bound to const reference. That is,
A & x = A(); //error
const A & y = A(); //ok
I also know that in the second case (above), the lifetime of the temporary created out of A()
extends till the lifetime of const reference (i.e y
).
But my question is:
Can the const reference which is bound to a temporary, be further bound to yet another const reference, extending the lifetime of the temporary till the lifetime of second object?
I tried this and it didn't work. I don't exactly understand this. I wrote this code:
struct A
{
A() { std::cout << " A()" << std::endl; }
~A() { std::cout << "~A()" << std::endl; }
};
struct B
{
const A & a;
B(const A & a) : a(a) { std::cout << " B()" << std::endl; }
~B() { std::cout << "~B()" << std::endl; }
};
int main()
{
{
A a;
B b(a);
}
std::cout << "-----" << std::endl;
{
B b((A())); //extra braces are needed!
}
}
Output (ideone):
A()
B()
~B()
~A()
-----
A()
B()
~A()
~B()
Difference in output? Why the temporary object A()
is destructed before the object b
in the second case? Does the Standard (C++03) talks about this behavior?