C++ Library Extensions 2022.12.09
To help learn modern C++ programming
041-move_semantic.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
5
7{
8 private:
9 int m_member;
10
11 public:
12 CopyOrMove(int m=int{}): m_member{ m }
13 {
14 stream << "Default constructor called" << endl;
15 }
16
17 CopyOrMove(const CopyOrMove& right_hand_side):
18 m_member{right_hand_side.m_member}
19 {
20 stream << "Copy Constructor called" << endl;
21 }
22
23 int* operator&() { return &this->m_member; }
24
25 CopyOrMove& operator = (const CopyOrMove& right_hand_side)
26 {
27 stream << "Copy operator called" << endl;
28
29 if(this != std::addressof(right_hand_side))
30 {
31 this->m_member = right_hand_side.m_member;
32 }
33
34 return *this;
35 }
36
37 CopyOrMove(CopyOrMove&& right_hand_side)
38 : m_member{ std::move(right_hand_side.m_member) }
39 {
40 stream << "Move constructor callled" << endl;
41 }
42
43 CopyOrMove& operator=(CopyOrMove&& right_hand_side)
44 {
45 stream << "Move assignment called" << endl;
46
47 if(this != std::addressof(right_hand_side))
48 {
49 this->m_member = std::move(right_hand_side.m_member);
50 }
51
52 return *this;
53 }
54
56 {
57 stream << "Destructor called"<< endl;
58 }
59};
60
62{
63 CopyOrMove obj{n};
64
65 return obj;
66}
67
69{
70 std::vector<CopyOrMove> container(2);
71
72 for(size_t i = 0; i < container.size(); ++i)
73 container[i] = CopyOrMove{ (int)i };
74}
75
77{
78 std::vector<CopyOrMove> container; container.reserve(2);
79
80 for(size_t i = 0; i < container.capacity(); ++i)
81 container.emplace_back( CopyOrMove{ (int)i } );
82}
83
84void do_this()
85{
86 std::vector<CopyOrMove> container; container.reserve(2);
87
88 for(size_t i = 0; i < container.capacity(); ++i)
89 container.emplace_back( (int)i );
90}
91
92int main()
93{
94 // auto o = make_copy_or_move(5);
96
97 stream << endl << endl;
98
99 do_this();
100
101 stream << endl << endl;
102
103
104 or_do_this();
105}
106
tpf::sstream stream
void don_t_do_this()
void better_but_not_perfect()
auto endl
CopyOrMove make_copy_or_move(int n)
int main()
void do_this()
CopyOrMove(CopyOrMove &&right_hand_side)
CopyOrMove & operator=(CopyOrMove &&right_hand_side)
CopyOrMove & operator=(const CopyOrMove &right_hand_side)
CopyOrMove(int m=int{})
CopyOrMove(const CopyOrMove &right_hand_side)
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.