[2018年5月10号]C++ primer 课后练习第十三章 拷贝控制

13.39
class StrVec {
public:
    StrVec():emlemnts(nullptr),first_free(nullptr),cap(nullptr){}
    StrVec(const StrVec&);
    StrVec& operator=(StrVec&);
    ~StrVec();
    void push_back(const string&);
    string* begin()const { return emlemnts; }
    string* end()const { return first_free; }
    size_t size() { return first_free - emlemnts; };
    size_t capacity() { return cap - emlemnts; };
    
private:
    string* emlemnts;
    string* first_free;
    string* cap;
    static allocator<string > alloc;
    pair<string* , string* > alloc_n_copy(const string *, const string *);
    void chk_n_alloc(){if(size() == capacity()){reallocate();}}
    void reallocate();
    void free();

};
StrVec::~StrVec(){
    free();
}
void StrVec::push_back(const string& s){
    chk_n_alloc();
    alloc.construct(first_free++,s);
}
StrVec::StrVec(const StrVec& s){
    auto tmpAlloc = alloc_n_copy(s.begin(), s.end());
    emlemnts = tmpAlloc.first;
    emlemnts = tmpAlloc.second;
}
StrVec& StrVec::operator=(StrVec& s){
    auto tmpAlloc = alloc_n_copy(s.begin(), s.end());
    free();
    emlemnts = tmpAlloc.first;
    first_free = tmpAlloc.second;
    return *this;
}
void StrVec::free(){
    for(auto p = first_free; p != emlemnts;){
        alloc.destroy(--p);
    }
    alloc.deallocate(emlemnts, capacity());
}
void StrVec::reallocate() {
    auto newcapacity = size()? 2*size():1;
    auto newdata = alloc.allocate(newcapacity);
    auto dest = newdata;
    auto elem = emlemnts;
    for(size_t i = 0 ; i != size(); i ++)
        alloc.construct(dest++,move(*elem++));
    free();
    emlemnts = newdata;
    first_free = dest;
    cap = emlemnts +newcapacity;
}

猜你喜欢

转载自blog.csdn.net/qq_22478401/article/details/80262518