Consider the following code:
#include <iostream>
struct A {
const char *name;
A() : name("A") {
std::cout << "A()\n";
}
virtual ~A() {
std::cout << "~A()\n";
}
};
class B {
const A& a;
public:
B() : a(A()) {
};
void print_data() const {
std::cout << a.name << '\n';
}
~B() {
std::cout << "~B()\n";
}
};
int main() {
B b;
b.print_data();
return 0;
}
The output from GCC 4.4 is:
A() ~A() A ~B()
This looks strange to me. I would have expected either a copy of the temporary instance of A being bound to the B::a or that temporary itself being destructed during ~B().
Basically, I thought B::a is always a valid reference during the life of b. In fact b.print_data() works apparently and the compiler does not give any warning.
What does the standard c++98/03 say about this matter?
Constant references don’t prolong the life of temporaries in classes, period. It’s just like that. They only do it in
Foo const& f = Foo();wherefooreturns by-value, but that’s it.§12.2 [class.temporary]