I am just beginner in move operation in c++11, so playing with it. But found something which i am not able to understand.
#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!!
}
I was expecting that b = std::move(a)
operation would behave something different because i am applying move on object a second time but it is copying left side object b to right hand side object a, this part i don't understand.
Or i have done something wrong in programming. Please help if i am doing something wrong in move operation.
EDIT: I know this is undefined behavior. My doubt is if i will do it again then it is copying from object a to object b, and if again i will do the same thing then will copy object b to object a?
Hence it is copying form left to right and right to left why?
You can't move from the same object twice.
After you first moved a
into b
, a
had a "valid but unspecified state" (can't remember the exact terminology). Then, you attempted to move a
into b
again! Now all heck has broken loose. (I suspect that, internally, the data pointers have just been swapped around.)
Simply don't do this. I see no reason to want to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With