#include <iostream>
using namespace std;
class Someclass
{
public:
~Someclass()
{
cout << "Someclass Dtor called" << endl;
}
};
int main()
{
Someclass obj;
{
Someclass&& ref = move(obj);
}
// At this point why the dtor is not called ? Because the reference went out of scope
cout << "Ending program" << endl;
return 0;
}
上面的代码输出如下:
节目结束
某个班主任打来电话
但是我的疑问是为什么输出不是这个?
某个班主任打来电话
节目结束
当引用超出范围时,不应该调用Someclass的dtor吗?
当引用超出范围时,不应该调用 Someclass 的 dtor 吗?
不。 (l-or-r)引用是现有对象的别名或替代名称。它提供了一种通过另一个名称访问对象的方法。它不拥有该对象。
因此当这一行:
{
Someclass&& ref = move(obj);
}
rvalue
ref
超出范围,唯一的别名是超出范围,而不是实际对象。