Created
November 1, 2019 12:56
-
-
Save raytroop/e23b5c88f95813a978308d24009a3e8e to your computer and use it in GitHub Desktop.
copy-and-move-assignment-operators-for-a-class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using std::cout; | |
using std::endl; | |
class A { | |
public: | |
A(int x): mem_(x){} | |
A& operator=(const A& other) { | |
cout << "copy assignment operator" << endl; | |
mem_ = other.mem_; | |
} // `obja = objb;` & `objc = std::move(obja);` both work | |
A& operator=(A&& other) { | |
cout << "move assignment operator" << endl; | |
mem_ = other.mem_; | |
other.mem_ = 99; | |
} // only `objc = std::move(obja);` work | |
private: | |
int mem_; | |
}; | |
int main() { | |
A obja(1); | |
A objb(2); | |
A objc(3); | |
obja = objb; | |
objc = std::move(obja); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment