classTest { private: char* pc; public: Test(); Test(const Test & t); Test(Test && t);//移动构造函数。因为要更改t,所以不能加上const ~Test(); Test operator+(const Test& t)const; }
Test::Test() { pc = newchar[100]; for(int i =0;i<100;++i){pc[i]=i;} } Test::Test(const Test& t) { pc = newchar[100]; for(int i=0;i<100;++i){pc[i]=t.pc[i];} } Test::Test(Test&& t) { pc=t.pc; t.pc=nullptr;//pc和t.pc指向同一块内存,调用析构时可能会出现问题,不能对同一块地址delete两次 //所以将t.pc设置为空地址,因为delete空指针是可以的 } Test::~Test() { delete [] pc; } Test Test::operator+(const Test& t) const { Test temp ; for (int i = 0; i < 100; ++i) { temp.pc[i] = this->pc[i]+t.pc[i]; } return temp; }
intmain() { Test one; Test two = one;//调用普通的拷贝构造。因为one是左值 Test three; Test four(one+three);//调用移动构造函数。因为one+three为右值 } //在c++98没有引入右值引用时,如果实参为右值,const引用形参将执行一个临时变量