Just a short snippet illustrating the basics of object construction in C++11.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
using namespace std;

class A {
private:
int x;
public:
static void f(A a) {}

static A create() {
return A(3);
}

A() {
// cout << "empty ctor" << endl;
}

explicit A(int x_) : x{x_} {
// cout << "init ctor" << endl;
}

A(const A& other) {
cout << "copy ctor" << endl;
x = other.x;
}

A& operator=(const A& other) {
cout << "assignment copy" << endl;
x = other.x;
return *this;
}

A(A&& other) : x{move(other.x)} {
cout << "move ctor" << endl;
}

A& operator=(A&& other) {
cout << "assignment move" << endl;
if (this != &other) {
x = move(other.x);
}
return *this;
}
};

int main()
{
A a{3};

// as if A is an primitive type, pass by value
// copy ctor; the two ways are identical
auto b = a;
// auto b{a};

// call empty ctor
A c;
// assignment copy
c = b;

// implicit conversion from int to A; explicit prevents such conversion
// additionally, copy-constructor can be disabled via this specifier as well
// A::f(3);

// copy elision; equivalent to direct initialization
auto d = A::create();
// auto d = A(3);

// forcing to call move ctor; identical
auto e = static_cast<A&&>(A::create());
// auto e = move(A::create());

A f;
// assignment move
f = A::create();

return 0;
}
1
2
3
4
5
$ clang++ -std=c++11 -stdlib=libc++ test.cc && ./a.out
copy ctor
assignment copy
move ctor
assignment move

Reference