Commit b7d3599e49edf00d582bd4d86230d2855d22748d
1 parent
5dc62c6a
Fix in move example
Showing
1 changed file
with
36 additions
and
39 deletions
examples05/04-unique_ptr/02-move.cpp
@@ -2,49 +2,46 @@ | @@ -2,49 +2,46 @@ | ||
2 | #include <memory> | 2 | #include <memory> |
3 | 3 | ||
4 | class Example { | 4 | class Example { |
5 | - public: | ||
6 | - int* val; | ||
7 | - | ||
8 | - Example(Example&& rhs) : val(rhs.val) | ||
9 | - { | ||
10 | - rhs.val = nullptr; | ||
11 | - std::cout << "Example::Example(Example &&)" << std::endl; | ||
12 | - } | ||
13 | - | ||
14 | - Example& operator=(Example&& rhs) // buggy | ||
15 | - { | ||
16 | - val = rhs.val; | ||
17 | - rhs.val = nullptr; | ||
18 | - std::cout << "Example::operator=(Example &&)" << std::endl; | ||
19 | - return *this; | ||
20 | - } | ||
21 | - | ||
22 | - Example() : val(new int(0)) | ||
23 | - { | ||
24 | - std::cout << "Example::Example()" << std::endl; | ||
25 | - } | ||
26 | - | ||
27 | - Example(int a) : val(new int(a)) | ||
28 | - { | ||
29 | - std::cout << "Example::Example(" << a << ")" << std::endl; | ||
30 | - } | ||
31 | - | ||
32 | - ~Example() | ||
33 | - { | ||
34 | - delete val; | ||
35 | - std::cout << "Example::~Example()" << std::endl; | ||
36 | - } | 5 | +public: |
6 | + int *val; | ||
7 | + | ||
8 | + Example(Example &&rhs) : val(rhs.val) { | ||
9 | + rhs.val = nullptr; | ||
10 | + std::cout << "Example::Example(Example &&)" << std::endl; | ||
11 | + } | ||
12 | + | ||
13 | + Example &operator=(Example &&rhs) // buggy | ||
14 | + { | ||
15 | + if (&rhs == this) | ||
16 | + return *this; | ||
17 | + val = rhs.val; | ||
18 | + rhs.val = nullptr; | ||
19 | + std::cout << "Example::operator=(Example &&)" << std::endl; | ||
20 | + return *this; | ||
21 | + } | ||
22 | + | ||
23 | + Example() : val(new int(0)) { | ||
24 | + std::cout << "Example::Example()" << std::endl; | ||
25 | + } | ||
26 | + | ||
27 | + Example(int a) : val(new int(a)) { | ||
28 | + std::cout << "Example::Example(" << a << ")" << std::endl; | ||
29 | + } | ||
30 | + | ||
31 | + ~Example() { | ||
32 | + delete val; | ||
33 | + std::cout << "Example::~Example()" << std::endl; | ||
34 | + } | ||
37 | }; | 35 | }; |
38 | 36 | ||
39 | -int main() | ||
40 | -{ | ||
41 | - Example a(3); | 37 | +int main() { |
38 | + Example a(3); | ||
42 | 39 | ||
43 | - Example b = std::move(a); | 40 | + Example b = std::move(a); |
44 | 41 | ||
45 | - Example c(Example(4)); | 42 | + Example c(Example(4)); |
46 | 43 | ||
47 | - Example d; | 44 | + Example d; |
48 | 45 | ||
49 | - d = std::move(b); | 46 | + d = std::move(b); |
50 | } | 47 | } |