我只是 c++11 中 move 操作的初学者,所以玩它。但是发现了一些我无法理解的东西。
#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)
操作会有所不同,因为我第二次在对象 a 上应用 move ,但它正在向左复制侧面对象b 到右侧对象a,这部分我不明白。
或者我在编程中做错了什么。 如果我在 move 操作中做错了什么,请帮助。
编辑: 我知道这是未定义的行为。我怀疑我是否会再做一次,然后它从对象 a 复制到对象 b,如果我再次做同样的事情,那么将复制对象 b 反对a?
因此它是从左到右和从右到左复制表格,为什么?
最佳答案
您不能从同一个对象 move 两次。
在你第一次将 a
move 到 b
之后,a
有一个“有效但未指定的状态”(不记得确切的术语) .然后,您再次尝试将 a
move 到 b
!现在一切都乱套了。 (我怀疑,在内部,数据指针刚刚被交换了。)
千万不要这样做。我认为没有理由想要这样做。
关于c++ - 同一对象的双 move 是从左向右复制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37112686/