Skip to content

Instantly share code, notes, and snippets.

@LarryRuane
Created January 31, 2023 02:21
Show Gist options
  • Save LarryRuane/6cf6e653ccbe9c055b06cd1e5413badd to your computer and use it in GitHub Desktop.
Save LarryRuane/6cf6e653ccbe9c055b06cd1e5413badd to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
class X {
public:
int i;
// ordinary cons X y(5):
X(int x) : i(x) { cout << "constructor " << i; }
// default cons X x:
X() { cout << "default constructor set i=99 "; i = 99; }
// copy cons X z(y):
//X(const X&) {
X(const X& a) {
i = a.i * 2;
cout << "copy constructor " << i << " " << a.i << " ";
}
// move cons X c(std::move(x))
X(X&& x) {
cout << "move constructor " << x.i << " ";
}
// copy assignment y = x
X& operator=(const X& x) {
i = x.i+1;
cout << "copy assignment(+1) " << x.i << " ";
}
// move assignment
X& operator=(X&& x) {
cout << "move assignment " << x.i << " ";
}
};
// return copy elision
X& f() {
X x;
int i;
int* ip = new int;
cout << "f: x.i " << x.i << " &x " << &x << " &i " << &i << " ip " << ip << " ";
return x;
}
int* return_intptr() {
int i;
cout << "return_intptr &i " << &i << " ";
return &i;
}
int main() {
int i;
cout << __LINE__ << " "; X y(5); cout << endl;
cout << __LINE__ << " "; X x; cout << x.i << endl;
cout << __LINE__ << " "; y = x; cout << y.i << endl;
cout << __LINE__ << " "; X z(y); cout << z.i << endl;
cout << __LINE__ << " "; x.i = 77; cout << endl;
cout << __LINE__ << " "; y = std::move(x); cout << endl;
cout << __LINE__ << " "; X& a = f(); cout << "&a.i " << &a.i << " &i " << &i << endl;
cout << __LINE__ << " "; X mc(f()); cout << endl;
cout << __LINE__ << " "; cout << y.i << endl;
cout << __LINE__ << " "; int* ip = return_intptr(); cout << "&ip " << ip << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment