从实现上讲,std::move 基本等同于一个类型转换:static_cast<T&&>(lvalue);,函数原型如下:
template<class _Ty>
_NODISCARD constexpr remove_reference_t<_Ty>&& move(_Ty&& _Arg) _NOEXCEPT
{ // forward _Arg as movablereturn (static_cast<remove_reference_t<_Ty>&&>(_Arg));
}
代码如下:
#include <iostream>
#include <list>
using namespace std;class Test
{
public:Test() :m_num(new int(100)){cout << "construct" << endl;cout << "address = " << m_num << endl;}Test(const Test & a) :m_num(new int(*a.m_num)){cout << "copy construct" << endl;}//有右值引用的构造函数称为移动构造函数//移动构造函数 -> 复用其他对象中的资源(堆内存)//m_num 浅拷贝Test(Test && a) :m_num(a.m_num){a.m_num = nullptr;cout << "move construct" << endl;}~Test(){cout << "destruct" << endl;delete m_num;}public:int *m_num;
};Test&& getobj()//将亡值
{return Test();
}Test getobj01()
{Test t;return t;
}int main()
{//通过一个匿名对象给一个右值初始化,再次使用这个t2会被编译器看做是一个左值,t2是左值引用。Test && t2 = getobj();cout << "address = " << t2.m_num << endl;//Test && t3 = t2;//t2会被编译器看做是一个左值Test && t3 = move(t2);Test t = getobj01();//t为左值Test &&t4 = move(t);list<string> ls1{ "hello","wordl","nihao","shijie" };list<string> ls2 = ls1;list<string> ls3 = move(ls1);//如果以后不用ls1了,就可以用move,减少拷贝次数,提高效率return 0;
}