-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmoveonly.cpp
110 lines (91 loc) · 2.52 KB
/
moveonly.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
105
106
107
108
109
110
// {"category": "C++11", "notes": "Move only types"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <vector>
#include <strsafe.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Move only types
//
//------------------------------------------------------------------------------
class text
{
char* m_text = nullptr;
public:
text() = default;
text(const text&) = delete;
text& operator=(const text&) = delete;
text(text&& other) noexcept
{
*this = move(other);
}
text& operator=(text&& other) noexcept
{
if (this != &other)
{
delete[] m_text;
m_text = other.m_text;
other.m_text = nullptr;
}
return *this;
}
text operator+(const text& other) &&
{
size_t size = strlen(*this) + strlen(other) + 1;
resize(size);
StringCchCatA(m_text, size, other);
return move(*this);
}
text(_In_opt_ const char* cstring)
{
if (cstring != nullptr)
{
size_t size = strlen(cstring) + 1;
resize(size);
StringCchCopyA(m_text, size, cstring);
}
}
~text()
{
delete[] m_text;
}
operator const char*() const
{
return (m_text != nullptr) ? m_text : "";
}
private:
void resize(size_t size)
{
char* cstring = new char[size];
StringCchCopyA(cstring, size, *this);
delete m_text;
m_text = cstring;
}
};
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
text lValue;
lValue = text("L-value");
vector<text> textVector;
textVector.push_back(text("R-value"));
textVector.push_back(move(lValue));
cout << R"(lValue = ")" << lValue << R"(")" << endl;
cout << R"(textVector[0] = ")" << textVector[0] << R"(")" << endl;
cout << R"(textVector[1] = ")" << textVector[1] << R"(")" << endl;
text moved = move(textVector[0]);
cout << R"(moved = ")" << moved << R"(")" << endl;
cout << R"(textVector[0] = ")" << textVector[0] << R"(")" << endl;
cout << R"(textVector[1] = ")" << textVector[1] << R"(")" << endl;
lValue = text("hello") + text(", world");
cout << lValue << endl;
cout << text("abc") + text("123") << endl;
return 0;
}