
class CObject {
public:CObject(string str):m_str(str) {cout << "构造函数" << endl;}CObject(const CObject& obj) {m_str = string(obj.m_str);cout << "拷贝构造函数" << endl;}CObject(CObject &&obj) {m_str = move(obj.m_str);cout << "移动构造函数" << endl;}void show() {cout << "m_str=" << m_str << endl;}private:string m_str;};//真正的移动发生在:
//移动构造函数
//移动赋值运算符
void test_obj(CObject&& obj) {//不一定发生移动构造obj.show();//这样子会触发移动构造CObject newObj = move(obj);}//右值绑定到左值会触发移动语义
void test_obj2(CObject obj) {//如果传入的是右值会发生移动构造obj.show();
}
调用:
CObject obj("xiaohai");test_obj(move(obj));obj.show();//输出空,理论上不应该调用