-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathString_ex44.h
85 lines (72 loc) · 1.6 KB
/
String_ex44.h
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
#ifndef STRING_H_
#define STRING_H_
#include <memory>
#include <algorithm>
#include <cstring>
class String
{
public:
String();
String(const char*);
String(const String&);
String& operator=(const String&);
char *begin() const { return elements; }
char *end() const { return first_free; }
~String();
private:
std::pair<char*, char*> alloc_n_copy(const char*, const char*);
void free();
std::allocator<char> alloc;
char *elements;
char *first_free;
};
std::pair<char*, char*> String::alloc_n_copy(const char *begin, const char *end)
{
char *p = alloc.allocate(end - begin);
// for(auto iter = begin; iter != end; ++iter)
// alloc.construct(iter, *iter);
return{p, std::uninitialized_copy(begin, end, p)};
}
String::String(const char* cp)
{
size_t n = strlen(cp);
auto newstr = alloc_n_copy(cp, cp + n);
elements = newstr.first;
first_free = newstr.second;
// char* p = alloc.allocate(n);
// for(int i = 0; i < n; ++i)
// alloc.construct(p+i, *(cp+i));
}
String::String()
{
String("");
}
String::String(const String &rhs)
{
auto newstr = alloc_n_copy(rhs.begin(), rhs.end());
elements = newstr.first;
first_free = newstr.second;
}
void String::free()
{
if(elements)
{
std::for_each(elements, first_free, [this](char cp){ alloc.destroy(&cp); });
alloc.deallocate(elements, first_free - elements);
}
}
String& String::operator=(const String& rhs)
{
auto newstr = alloc_n_copy(rhs.begin(), rhs.end());
free();
elements = newstr.first;
first_free = newstr.second;
return *this;
}
String::~String()
{
// for(auto iter = elements; iter != first_free; )
// alloc.destroy(--iter);
free();
}
#endif