Skip to content

Instantly share code, notes, and snippets.

@jacob-faber
Last active March 28, 2016 01:01
Show Gist options
  • Save jacob-faber/c2cfeb5408af711e0761 to your computer and use it in GitHub Desktop.
Save jacob-faber/c2cfeb5408af711e0761 to your computer and use it in GitHub Desktop.
COPY & MOVE Semantics
#include <iostream>
using namespace std;
class A {
public:
A(int id) : id(id) {
cout << "CONSTRUCTOR ID" << endl;
}
A() {
cout << "CONSTRUCTOR" << endl;
}
~A() {
cout << "DESTRUCTOR" << endl;
}
A(const A &other) {
cout << "COPY CONSTRUCTOR" << endl;
}
A(A &&other) : id(0) {
cout << "MOVE CONSTRUCTOR" << endl;
}
A &operator=(const A &other) {
cout << "COPY on Lvalue" << endl;
return *this;
}
A &operator=(A &&other) {
cout << "MOVE on Rvalue" << endl;
return *this;
}
// Invokes move constructor
A &&move_test() {
A a(11);
return move(a);
}
// DANGER! Invokes copy constructor, but after a has been destructed
A &copy_test() {
A a(12);
return a;
}
// Passes by value
A value_test() {
A a(12);
return a;
}
// parameter is created by COPY constructor
// return value is created by MOVE constructor
A move_arg_test1(A a) {
// return move(a); // same
return a;
}
// parameter is passed by address
// return value is created by COPY constructor
A &move_arg_test2(A &a) {
return a;
}
// parameter is passed by address (takes only Rvalue)
// return value is created by MOVE constructor
A &&move_arg_test3(A &&a) {
return move(a);
}
private:
int id;
};
int main() {
A a1(6);
A a2(7);
// A a2 = A(4); // calls constructors ???
// A c = a1; // calls COPY constructor
// a1 = a2; // calls COPY operator= on Lvalue
// a1 = a2.move_test(); // calls MOVE operator= on Rvalue
// a1 = A(4); // calls MOVE operator= on Rvalue
A a(8);
// A d = a.move_arg_test1(a);
// A d = a.move_arg_test2(a);
// A d = a.move_arg_test3(A(4));
// A d = a.copy_test();
// A e = a.value_test();
// A c = a.move_test();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment