forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex14_26_String.h
83 lines (69 loc) · 2.43 KB
/
ex14_26_String.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
#ifndef CP5_STRING_H__
#define CP5_STRING_H__
#include <memory>
#include <iostream>
#ifndef _MSC_VER
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif
//===================================================================================
//
// |s|t|r|i|n|g|\0|-------------------|
// ^ ^ ^ first_free ^
// elements last_elem cap
//
//===================================================================================
class String
{
friend std::ostream& operator<<(std::ostream&, const String&);
friend std::istream& operator>>(std::istream&, String&);
friend bool operator==(const String&, const String&);
friend bool operator!=(const String&, const String&);
friend bool operator< (const String&, const String&);
friend bool operator> (const String&, const String&);
friend bool operator<=(const String&, const String&);
friend bool operator>=(const String&, const String&);
public:
String() : String("") { }
String(const char *);
String(const String&);
String& operator=(const String&);
String(String &&) NOEXCEPT;
String& operator=(String&&)NOEXCEPT;
~String();
void push_back(const char);
char* begin() const { return elements; }
char* end() const { return last_elem; }
char& operator[](size_t n) { return elements[n]; }
const char& operator[](size_t n) const { return elements[n]; }
const char *c_str() const { return elements; }
size_t size() const { return last_elem - elements; }
size_t length() const { return size(); }
size_t capacity() const { return cap - elements; }
void reserve(size_t);
void resize(size_t);
void resize(size_t, char);
private:
std::pair<char*, char*> alloc_n_copy(const char*, const char*);
void range_initializer(const char*, const char*);
void free();
void reallocate();
void alloc_n_move(size_t new_cap);
void chk_n_alloc() { if (first_free == cap) reallocate(); }
private:
char *elements;
char *last_elem;
char *first_free;
char *cap;
std::allocator<char> alloc;
};
std::ostream& operator<<(std::ostream&, const String&);
std::istream& operator>>(std::istream&, String&);
bool operator==(const String&, const String&);
bool operator!=(const String&, const String&);
bool operator< (const String&, const String&);
bool operator> (const String&, const String&);
bool operator<=(const String&, const String&);
bool operator>=(const String&, const String&);
#endif