#include <iostream> using namespace std; class A { public: ~A(){ cout << "end A" << endl; };
void Show()const{ cout << "show" << endl; } };
A fun() { return A(); }
int main() { const A &a = fun(); a.Show(); // puts("a"); }
[解决办法] 函数返回引用,不是临时对象。
fun()
返回的确实是个A的临时对象。
Show()
返回的是个引用,不是临时对象,所以不能延长它返回东西的生命周期,但关键问题是它引用的是fun()返回的一个临时对象,于是语句结束,fun()返回的临时对象就被回收了~ [解决办法] The language says "temporaries die at the end of the statement, unless they are bound to const reference, in which case they die when the reference goes out of scope". Applying that rule, it seems a is already dead at the beginning of the next statement, since it's not bound to const reference (the compiler doesn't know what fun() returns). This is just a guess however. [解决办法] 我看了下原文,是这样说的:
So the rule is that a temporary bound to a reference persists for the lifetime of the reference initialized or until the end of the scope in which the temporary is created, whichever comes first.