c++ - 为什么 std::move 返回的对象不立即销毁

标签 c++ c++11

我测试了以下代码:

#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/

相关文章:

c++ - 获得一个字节的随机性

c++ - 通过引用传递截断的 vector

c++ - 为程序全局设置 Linux 上的默认堆栈大小

c++ - 为函数创建 openmp 线程

C++ 基类引用用不同的派生类对象初始化

c++ - 尝试使用 C++ 移动构造函数...但失败了

c++ - 结构成员的运行时对齐

c++ - 如何在 Visual C++ 2012 中 sleep 不受系统时钟调整影响的固定时间

c++ - 排序获取最大数

c++ - 如何在等待 std::cin 时终止 C++11 线程?