64,648
社区成员
发帖
与我相关
我的任务
分享
class A
{
public:
~A(){ cout << "end A" << endl; };
A& Show(){ cout << "show" << endl;return *this; }
};
A fun()
{
return A();
}
A &a = fun().Show(); // 这里
const A& fun()
{
return A();
}
const A &a = fun();
fun()
返回的确实是个A的临时对象。
Show()
返回的是个引用,不是临时对象,所以不能延长它返回东西的生命周期,但关键问题是它引用的是fun()返回的一个临时对象,于是语句结束,fun()返回的临时对象就被回收了~#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");
}
const A &a = fun().Show();