-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy path02_copy_move.cpp
More file actions
51 lines (43 loc) · 1.67 KB
/
02_copy_move.cpp
File metadata and controls
51 lines (43 loc) · 1.67 KB
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
#include <algorithm>
#if __cplusplus >= 201103L
struct NonCopyable {
NonCopyable() = default;
NonCopyable(const NonCopyable &) = delete;
NonCopyable &operator=(const NonCopyable &) = delete;
// NOTE: also non-movable
// without defined move constructor and assignment operator
// NonCopyable(NonCopyable &&) = default;
// NonCopyable &operator=(NonCopyable &&) = default;
};
#else
struct NonCopyable {
NonCopyable() {}
private:
NonCopyable(const NonCopyable &);
NonCopyable &operator=(const NonCopyable &);
};
#endif
class MyType : NonCopyable {};
struct MyTypeV2 {
MyTypeV2() = default;
MyTypeV2(const MyTypeV2 &) = delete;
MyTypeV2 &operator=(const MyTypeV2 &) = delete;
MyTypeV2(MyTypeV2 &&) = delete;
MyTypeV2 &operator=(MyTypeV2 &&) = delete;
virtual ~MyTypeV2() = default;
};
int main() {
// in C++17+ this works despite non-copyablility due to mandatory copy elision
auto my_object = MyType{};
auto my_better_object = MyTypeV2{};
/* clang-format off */
// auto my_object2 = my_object; // compilation error: non-copyable
// auto my_object3{my_object}; // compilation error: non-copyable
// auto my_object2 = std::move(my_object); // compilation error: non-moveable, but can be
// auto my_object3{std::move(my_object)}; // compilation error: non-moveable, but can be
//auto my_better_object2= my_better_object; // compilation error: non-copyable
//auto my_better_object3{my_better_object}; // compilation error: non-copyable
//auto my_better_object4= std::move(my_better_object); // compilation error: non-moveable
//auto my_better_object5{std::move(my_better_object)}; // compilation error: non-moveable
/* clang-format on */
}