forked from 0voice/cpp_new_features
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path002_grammar_rvalue_reference.cpp
104 lines (93 loc) · 2 KB
/
002_grammar_rvalue_reference.cpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "stdio.h"
#include <string>
#include <iostream>
using namespace std;
class MyString
{
public:
MyString() :m_pData(NULL), m_nLen(0)
{
cout << "MyString()" << endl;
}
MyString(const char *pStr) // 允许隐式转换
{
cout << "MyString(const char *pStr)" << endl;
m_nLen = strlen(pStr);
CopyData(pStr);
}
MyString(const MyString& other)
{
cout << "MyString(const MyString& other)" << endl;
if (!other.m_pData)
{
m_nLen = other.m_nLen;
DeleteData();
CopyData(other.m_pData);
}
}
MyString& operator=(const MyString& other)
{
cout << "MyString& operator=(const MyString& other)" << endl;
if (this != &other)
{
m_nLen = other.m_nLen;
DeleteData();
CopyData(other.m_pData);
}
return *this;
}
MyString(MyString&& other)
{
cout << "MyString(MyString&& other)" << endl;
m_nLen = other.m_nLen;
m_pData = other.m_pData;
other.m_pData = NULL;
}
MyString& operator=(MyString&& other)
{
cout << "MyString& operator=(const MyString&& other)" << endl;
if (this != &other)
{
m_nLen = other.m_nLen;
m_pData = other.m_pData;
other.m_pData = NULL;
}
return *this;
}
~MyString()
{
DeleteData();
}
private:
void CopyData(const char *pData)
{
if (pData)
{
m_pData = new char[m_nLen + 1];
memcpy(m_pData, pData, m_nLen);
m_pData[m_nLen] = '\0';
}
}
void DeleteData()
{
if (m_pData != NULL)
{
delete[] m_pData;
m_pData = NULL;
}
}
private:
char *m_pData;
size_t m_nLen;
};
MyString Fun()
{
MyString str = "hello world";
return str;
}
void main()
{
MyString str1 = "hello";
MyString str2(str1);
MyString str3 = Fun();
}