我测试了以下代码:
#include <iostream>
using namespace std;
class foo{
public:
foo() {cout<<"foo()"<<endl;}
~foo() {cout<<"~foo()"<<endl;}
};
int main()
{
foo f;
move(f);
cout<<"statement \"move(f);\" done."<<endl;
return 0;
}
输出是:
foo()
statement "move(f);" done.
~foo()
但是,我预计:
foo()
~foo()
statement "move(f);" done.
根据函数move的源码:
template<typename _Tp>
constexpr typename std::remove_reference<_Tp>::type&&
move(_Tp&& __t) noexcept
{ return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }
返回的对象是正确的值,为什么不立即销毁呢?
---------------------------------------------- --------------
我想我只是混淆了右值和右值引用。
我修改了我的代码:
#include <iostream>
template<typename _Tp>
constexpr typename /**/std::remove_reference<_Tp>::type /* no && */
/**/ mymove /**/ (_Tp&& __t) noexcept
{ return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }
using namespace std;
class foo{
public:
foo() {cout<<"foo() at "<<this<<endl;} /* use address to trace different objects */
~foo() {cout<<"~foo() at "<<this<<endl;} /* use address to trace different objects */
};
int main()
{
foo f;
mymove(f);
cout<<"statement \"mymove(f);\" done."<<endl;
return 0;
}
现在我得到了我一直期待的结果:
foo() at 0x22fefe
~foo() at 0x22feff
statement "mymove(f);" done.
~foo() at 0x22fefe
最佳答案
从对象移动不会改变它的生命周期,只会改变它的当前值。您的对象 foo
在从输出之后的 main
返回时被销毁。
此外,std::move
不会从对象移动。它只返回一个右值引用,其引用对象是对象,使其可能从对象中移动。
关于c++ - 为什么 std::move 返回的对象不立即销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15663539/