forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex13_49_String.cpp
65 lines (56 loc) · 1.3 KB
/
ex13_49_String.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
#include "ex13_49_String.h"
#include <algorithm>
std::pair<char*, char*> String::alloc_n_copy(const char* b, const char* e)
{
auto str = alloc.allocate(e - b);
return {str, std::uninitialized_copy(b, e, str)};
}
void String::range_initializer(const char* first, const char* last)
{
auto newstr = alloc_n_copy(first, last);
elements = newstr.first;
end = newstr.second;
}
String::String(const char* s)
{
char* sl = const_cast<char*>(s);
while (*sl) ++sl;
range_initializer(s, ++sl);
}
String::String(const String& rhs)
{
range_initializer(rhs.elements, rhs.end);
}
void String::free()
{
if (elements) {
std::for_each(elements, end, [this](char& c) { alloc.destroy(&c); });
alloc.deallocate(elements, end - elements);
}
}
String::~String()
{
free();
}
String& String::operator=(const String& rhs)
{
auto newstr = alloc_n_copy(rhs.elements, rhs.end);
free();
elements = newstr.first;
end = newstr.second;
return *this;
}
String::String(String&& s) NOEXCEPT : elements(s.elements), end(s.end)
{
s.elements = s.end = nullptr;
}
String& String::operator=(String&& rhs) NOEXCEPT
{
if (this != &rhs) {
free();
elements = rhs.elements;
end = rhs.end;
rhs.elements = rhs.end = nullptr;
}
return *this;
}