Skip to content

Instantly share code, notes, and snippets.

@raytroop
Created November 1, 2019 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raytroop/e23b5c88f95813a978308d24009a3e8e to your computer and use it in GitHub Desktop.
Save raytroop/e23b5c88f95813a978308d24009a3e8e to your computer and use it in GitHub Desktop.
copy-and-move-assignment-operators-for-a-class
#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