Skip to content

Commit 48c00e1

Browse files
committed
Create learn_move_semantics.cpp
1 parent 442c24c commit 48c00e1

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Notes/learn_move_semantics.cpp

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*****************************************************************//**
2+
* \file learn_move_semantics.cpp
3+
* \brief Brief introduction in move semantics in C++ with
4+
* move constructor (rvalue reference)
5+
* Compiler g++ optimizes the behaviour of the program
6+
* by bypassing all the copying and moving
7+
*
8+
* To compile on Windows:
9+
* $ g++ -o move.exe .\learn_move_semantics.cpp -std=c++11
10+
* $ .\move.exe
11+
*
12+
* \author Xuhua Huang
13+
* \date October 2021
14+
*********************************************************************/
15+
16+
#include <iostream> // std::cout
17+
#include <stdlib.h> // system()
18+
19+
/**
20+
* Class HasPtrMem Definition.
21+
* Stands for "Has Pointer Member"
22+
*/
23+
class HasPtrMem
24+
{
25+
public:
26+
/* Default Constructor */
27+
HasPtrMem() : ptr(new int(0)) {
28+
std::cout << __func__ << " at line: " << __LINE__ << "\n"
29+
<< "Default Construct: " << ++n_cstr << std::endl;
30+
}
31+
32+
/* Copy Constructor */
33+
HasPtrMem(const HasPtrMem& rhs) : ptr(new int(*rhs.ptr)) {
34+
std::cout << __func__ << " at line: " << __LINE__ << "\n"
35+
<< "Copy Constructor: " << ++n_cptr << std::endl;
36+
}
37+
38+
/* Move Constructor */
39+
HasPtrMem(HasPtrMem&& rhs) : ptr(rhs.ptr) {
40+
rhs.ptr = nullptr; // void the right-hand-side object internal pointer
41+
std::cout << __func__ << " at line: " << __LINE__ << "\n"
42+
<< "Move Constructor: " << ++n_mvtr << std::endl;
43+
}
44+
45+
/* Destructor */
46+
~HasPtrMem() {
47+
delete ptr;
48+
std::cout << __func__ << " at line: " << __LINE__ << "\n"
49+
<< "Destructor: " << ++n_dstr << std::endl;
50+
}
51+
52+
/* Definition of static integer members. */
53+
static int n_cstr; // number of times default constructor called
54+
static int n_cptr; // number of times copy constructor called
55+
static int n_mvtr; // number of times move constructor called
56+
static int n_dstr; // number of times destructor called
57+
// private:
58+
int* ptr;
59+
};
60+
61+
/* Define static variables for class hasPtrMem */
62+
int HasPtrMem::n_cstr = 0;
63+
int HasPtrMem::n_cptr = 0;
64+
int HasPtrMem::n_mvtr = 0;
65+
int HasPtrMem::n_dstr = 0;
66+
67+
HasPtrMem getTemp() {
68+
HasPtrMem temp;
69+
std::cout << "Resource from " << __func__ << ": "
70+
<< _HEX << temp.ptr << std::endl;
71+
72+
return temp;
73+
}
74+
75+
int main(void)
76+
{
77+
HasPtrMem h = getTemp();
78+
std::cout << "Resource from " << __func__ << ": "
79+
<< _HEX << h.ptr << std::endl;
80+
81+
system("pause");
82+
return 0;
83+
}

0 commit comments

Comments
 (0)