我只是c ++ 11移动操作的初学者,所以玩它。但是发现了一些我无法理解的东西。
#include <iostream>
using namespace std;
class A{
public:
A(){cout << "default ctor" << endl;}
A(const string& str):_str{str}{cout << "parameter ctor" << endl;}
A(A&& obj):_str{std::move(obj._str)}{cout << "move ctor" << endl;}
A& operator =(A&& rhs){_str = std::move(rhs._str);cout << "move assignment operation" << endl; return *this;}
void print(){cout << _str << endl;}
private:
string _str;
};
int main(){
A a("rupesh yadav"); // parameter ctor
A b(std::move(a)); // move ctor
cout << "print a: ";
a.print(); // NOT printing --> CORRECT!!
cout << "print b: ";
b.print(); // printing --> CORRECT!!
b = std::move(a); // i don't know may be silly but still lets do it WHY NOT!!!, could be just mistake??
cout << "print a: ";
a.print(); // printing --> WRONG!!
cout << "print b: ";
b.print(); // NOT printing --> WRONG!!
}
我期望该b = std::move(a)
操作会表现出不同的行为,因为我第二次在对象上应用移动,但它将左侧对象b复制到右侧对象a,这部分我不明白。
或者我在编程中做错了什么。如果我在移动操作中做错了什么,请帮忙。
编辑:我知道这是未定义的行为。我的疑问是我是否会再做一次,那么它是从对象a复制到对象b,如果我再次做同样的事情,那么会将对象b复制到对象a吗?
因此它是从左到右和从右到左复制表格,为什么?