【C++ Primer 第13章】5. 动态内存管理类

StrVec类的设计

题目描述:我们将实现标准库vector类的一个简化版本,我们所做的一个简化是不使用模板,我们类只用于string,因此,它被命名为StrVec。

 1 #include<iostream>
 2 #include<string>
 3 #include<memory>
 4 using namespace std;
 5 
 6 class StrVec {
 7 public:
 8     StrVec(): elements(nullptr), first_free(nullptr), cap(nullptr) {}
 9     StrVec(const StrVec &);
10     StrVec& operator=(const StrVec&);
11     ~StrVec() { free(); };
12 
13     void push_back(const string&);
14     size_t size() const { return first_free - elements; }
15     size_t capacity() const { return cap - elements; }
16     string *begin() const { return elements; }
17     string *end() const { return first_free; }
18 
19 private:
20     static allocator<string> alloc;
21     void chk_n_alloc() { if (size() == capacity()) reallocate(); }
22     pair<string*, string*> alloc_n_copy(const string*, const string *);
23     void reallocate();
24     string *elements;    //指向数组首元素的指针
25     string *first_free; //指向数组第一个空闲元素的指针
26     string *cap;         //指向数组尾后位置的指针
27 };
28 
29 StrVec::StrVec(const StrVec &s)
30 {
31     auto newdata = alloc_n_copy(s.begin(), s.end());
32     elements = newdata.first;
33     first_free = cap = newdata.second;
34 }
35 
36 StrVec& StrVec::operatot=(cost StrVec& rhs)
37 {
38     auto data = alloc_n_copy(rhs.begin(), rhs.end());
39     free();
40     elements = data.first;
41     first_free = cap = newdata.second;
42     return *this;
43 }
44 
45 void StrVec::()
46 {
47     if(elements)
48     {
49         for (auto p = first_free; p != elements; )
50             alloc.destroy(--p);
51         alloc.deallocate(elements, cap - elements);
52     }
53 }
54 
55 pair<string *, string *> StrVec::alloc_n_copy(const string *b, const string *e)
56 {
57     auto data = alloc.allocate(e - b);
58     return { data, uninitialized_copy(b, e, data) };
59 }
60 
61 void StrVec::push_back(const string& s)
62 {
63     chk_n_alloc();
64     alloc.construct(first_free++, s);
65 }
66 
67 void StrVec::reallocate()
68 {
69     auto newcapacity = size() ? 2 * size() : 1;
70     auto newdata = alloc.allocate(newcapacity);
71     auto dest = newdata;
72     auto elem = elements;
73     for (size_t i = 0; i != size(); ++i)
74         alloc.construct(dest++, std::move(*elem++));
75     free();
76     elements = newdata;
77     first_free = dest;
78     cap = elements + newcapacity;
79 }

猜你喜欢

转载自www.cnblogs.com/sunbines/p/9012501.html