move() 函数的用法也很简单,其语法格式如下:基于 move() 函数特殊的功能,其常用于实现移动语义。
move( arg )
其中,arg 表示指定的左值对象。该函数会返回 arg 对象的右值形式。#include <iostream> using namespace std; class movedemo{ public: movedemo():num(new int(0)){ cout<<"construct!"<<endl; } //拷贝构造函数 movedemo(const movedemo &d):num(new int(*d.num)){ cout<<"copy construct!"<<endl; } //移动构造函数 movedemo(movedemo &&d):num(d.num){ d.num = NULL; cout<<"move construct!"<<endl; } public: //这里应该是 private,使用 public 是为了更方便说明问题 int *num; }; int main(){ movedemo demo; cout << "demo2:\n"; movedemo demo2 = demo; //cout << *demo2.num << endl; //可以执行 cout << "demo3:\n"; movedemo demo3 = std::move(demo); //此时 demo.num = NULL,因此下面代码会报运行时错误 //cout << *demo.num << endl; return 0; }程序执行结果为:
construct!
demo2:
copy construct!
demo3:
move construct!
注意,调用拷贝构造函数,并不影响 demo 对象,但如果调用移动构造函数,由于函数内部会重置 demo.num 指针的指向为 NULL,所以程序中第 30 行代码会导致程序运行时发生错误。
#include <iostream> using namespace std; class first { public: first() :num(new int(0)) { cout << "construct!" << endl; } //移动构造函数 first(first &&d) :num(d.num) { d.num = NULL; cout << "first move construct!" << endl; } public: //这里应该是 private,使用 public 是为了更方便说明问题 int *num; }; class second { public: second() :fir() {} //用 first 类的移动构造函数初始化 fir second(second && sec) :fir(move(sec.fir)) { cout << "second move construct" << endl; } public: //这里也应该是 private,使用 public 是为了更方便说明问题 first fir; }; int main() { second oth; second oth2 = move(oth); //cout << *oth.fir.num << endl; //程序报运行时错误 return 0; }程序执行结果为:
construct!
first move construct!
second move construct
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有