13.23 有一定差異,我使用if判斷是否自我拷貝 本節(jié)使用先拷貝右側(cè)對象的方式來使自我拷貝正常運行
13.24 如果沒有定義析構(gòu)函數(shù),肯定會發(fā)生內(nèi)存泄露 如果沒有定義拷貝構(gòu)造函數(shù),當使用了拷貝構(gòu)造函數(shù)時,刪除一個對象會使和其他對象共用的內(nèi)存被釋放,其他對象則出現(xiàn)錯誤
13.25 拷貝構(gòu)造和拷貝賦值必須新建內(nèi)存,而不是和右側(cè)共用內(nèi)存
當shared_ptr計時器為0時,會自動的釋放,所以不需要析構(gòu)函數(shù)
13.26 @pezy
https://github.com/PYPARA/Cpp-PRimer/blob/master/ch13/ex13_26.h
#include <vector>#include <string>#include <initializer_list>#include <memory>#include <exception>using std::vector; using std::string;class ConstStrBlobPtr;class StrBlob {public: using size_type = vector<string>::size_type; friend class ConstStrBlobPtr; ConstStrBlobPtr begin() const; ConstStrBlobPtr end() const; StrBlob():data(std::make_shared<vector<string>>()) { } StrBlob(std::initializer_list<string> il):data(std::make_shared<vector<string>>(il)) { } // copy constructor StrBlob(const StrBlob& sb) : data(std::make_shared<vector<string>>(*sb.data)) { } // copyassignment Operators StrBlob& operator=(const StrBlob& sb); size_type size() const { return data->size(); } bool empty() const { return data->empty(); } void push_back(const string &t) { data->push_back(t); } void pop_back() { check(0, "pop_back on empty StrBlob"); data->pop_back(); } std::string& front() { check(0, "front on empty StrBlob"); return data->front(); } std::string& back() { check(0, "back on empty StrBlob"); return data->back(); } const std::string& front() const { check(0, "front on empty StrBlob"); return data->front(); } const std::string& back() const { check(0, "back on empty StrBlob"); return data->back(); }private: void check(size_type i, const string &msg) const { if (i >= data->size()) throw std::out_of_range(msg); }private: std::shared_ptr<vector<string>> data;};class ConstStrBlobPtr {public: ConstStrBlobPtr():curr(0) { } ConstStrBlobPtr(const StrBlob &a, size_t sz = 0):wptr(a.data), curr(sz) { } // should add const bool operator!=(ConstStrBlobPtr& p) { return p.curr != curr; } const string& deref() const { // return value should add const auto p = check(curr, "dereference past end"); return (*p)[curr]; } ConstStrBlobPtr& incr() { check(curr, "increment past end of StrBlobPtr"); ++curr; return *this; }private: std::shared_ptr<vector<string>> check(size_t i, const string &msg) const { auto ret = wptr.lock(); if (!ret) throw std::runtime_error("unbound StrBlobPtr"); if (i >= ret->size()) throw std::out_of_range(msg); return ret; } std::weak_ptr<vector<string>> wptr; size_t curr;};ConstStrBlobPtr StrBlob::begin() const // should add const{ return ConstStrBlobPtr(*this);}ConstStrBlobPtr StrBlob::end() const // should add const{ return ConstStrBlobPtr(*this, data->size());}StrBlob& StrBlob::operator=(const StrBlob& sb){ data = std::make_shared<vector<string>>(*sb.data); return *this;}int main(){ return 0;}新聞熱點
疑難解答