最近在補看《C++ Primer Plus》第六版,這的確是本好書,其中關于智能指針的章節解析的非常清晰,一解我以前的多處困惑。C++面試過程中,很多面試官都喜歡問智能指針相關的問題,比如你知道哪些智能指針?shared_ptr的設計原理是什么?如果讓你自己設計一個智能指針,你如何完成?等等……。而且在看開源的C++項目時,也能隨處看到智能指針的影子。這說明智能指針不僅是面試官愛問的題材,更是非常有實用價值。
C++通過一對運算符 new 和 delete 進行動態內存管理,new在動態內存中為對象分配空間并返回一個指向該對象的指針,delete接受一個動態對象的指針,銷毀對象并釋放與之相關的內存。然而這樣的動態內存的使用很危險,因為無法確保始終能在合適的時間釋放內存對象。如果忘記釋放內存,可能造成內存泄露;如果在尚有指針引用內存的情況下釋放內存,會產生非法訪問內存的指針。
C++11中,新的標準庫提供了兩種智能指針(smart pointer)類型來更安全地管理對象。智能指針的使用和常規指針類似,只是它們多了自動釋放所指向的對象的功能。兩種指針的區別在于管理底層指針的方式:shared_ptr允許多個指針指向同一個對象,unique_ptr不支持。標準庫還提供了weak_ptr這一弱指針,指向shared_ptr所管理的對象。三種類型都定義在頭文件memory中。
shared_ptr的使用和vector很相似,在尖括號內說明所指向對象的類型:
解引用一個智能指針就能獲得它所指向的對象,在if語句中使用智能指針可以判斷它指向的對象是否為空:
最安全的分配和使用shared_ptr的方法是調用名為make_shared這一標準庫函數。此函數在動態內存中分配并初始化它,返回指向此對象的shared_ptr。該函數定義在memory中。
make_shared的定義和shared_ptr相似,必須制定要創建對象的類型,如:
- // 指向一個值為1的int的shared_ptr
- shared_ptr<int> p3 = make_shared<int>)(1);
- // 指向一個值為“www”的string的shared_ptr
- shared_ptr<string> p4 = make_shared<string>(3, "w");
- // 指向一個初始化的int,值為0
- shared_ptr<int> p5 = make_shared<int>)();
也可以使用auto定義對象保存make_shared,可以省去書寫shared_ptr的麻煩。
shared——ptr中有一個關聯的指示器,稱為引用計數??梢钥醋鲆粋€計數器,每當shared_ptr對象進行拷貝操作,如用一個shared_ptr對象初始化另一個shared_ptr對象、作為函數的實參、作為函數返回值時,引用計數都會遞增(視為數值+1)。當賦予shared_ptr新值或者shared_ptr被銷毀時,引用計數遞減。當引用計數減為0,通過析構函數,shared_ptr自動銷毀所管理的對象,釋放內存。
需要注意的是,如果多個對象共享底層數據,當某一對象被銷毀,不能單方面銷毀底層數據,例如:
- Blob<string> b1;
- { // 新作用域
- Blob<string> b2 = { "x", "b", "b" };
- b1 = b2;
- } // 當離開局部作用域,b2被銷毀,然而b2中的元素xbb并不會被銷毀
- // b1指向最初由b2創建的元素,即“x”, "b", "b",b1依舊可以它們
weak_ptr是指向shared_ptr管理的對象的一種智能指針,然而它不控制所指向對象的生存期。將一個weak_ptr綁定在shared_ptr上,不會改變shared_ptr的引用計數,一旦最后一個shared_ptr的指向對象被摧銷毀,對象就會被釋放,有無weak_ptr并無卵影響。我的理解是,weak_ptr提供了指向shared_ptr底層數據的功能,控制了shared_ptr對底層數據的訪問。
因為weak_ptr指向的對象可能不存在(shared_ptr指向的最后一個對象被銷毀時),因而用它不能直接訪問對象,必須調用lock函數檢查其指向的對象是否存在。很容易寫出一個選擇語句進行控制:
- auto bb = make_shared<string>(2, 'b');
- weak_ptr<string> xbb(bb);
- if (shared_pr<int> np = xbb.lock()) { // np不為空條件成立
- // 在if語句內,np和xbb共享對象
- }
補充weak_ptr相關的函數,便于理解:
w.reset 將w置為空
w.use_count() 與w共享對象的個數
w.expired() 若w.use_count()為0,返回true,否則返回false
w.lock() 若w.expired()為true,返回一個空shared_ptr,否則返回一個指向w的對象的shared_ptr
加入《C++ Primer 5th》中的12.19題參照,題中和“智能指針和異常”并未在本篇隨筆中介紹
- #include <iostream>
- #include <string>
- #include <vector>
- #include <memory>
- #include <initializer_list>
- using namespace std;
- using std::string;
- using std::vector;
- class StrBlobPtr;
- class StrBlob {
- public:
- friend class StrBlobPtr; // 友元
- StrBlobPtr begin(); // 聲明StrBlob類中的begin()和end()
- StrBlobPtr end(); // 返回一個指向它自身的StrBlobPtr
- public:
- typedef vector<string>::size_type size_type; // 類型別名,size_type = vector<string>::size_type
- StrBlob::StrBlob(initializer_list<string> il) : data(make_shared<vector<string>>(il)) {}; // 接受一個initializer_list參數的構造函數將其參數傳 遞給對應的vector構造函數,通過拷貝列表
- StrBlob::StrBlob() : data(make_shared<vector<string>>()) {}; // 構造函數,初始化data成員,指向動態分配的vector 中的值初始化vector元素
- void push_back(const string &t) { data->push_back(t); }
- string& StrBlob::front() {
- check(0, "front on empty StrBlob");
- return data->front();
- }
- string& StrBlob::back() {
- check(0, "back on empty StrBlob");
- return data->back();
- }
- void StrBlob::pop_back() { // 刪除尾元素
- check(0, "pop_back empty StrBlob");
- return data->pop_back();
- }
- string& front() const { return data->front(); };
- string& back() const { return data->back(); };
- private:
- shared_ptr<vector<string>> data;
- void StrBlob::check(size_type i, const string &msg) const { // 檢查元素是否存在
- if (i >= data->size()) // 若不存在
- throw out_of_range(msg); // 拋出異常
- }
- };
- class StrBlobPtr {
- public:
- StrBlobPtr() : curr(0) {};
- StrBlobPtr(StrBlob &a, size_t sz = 0) : wptr(a.data), curr(sz) {};
- string & deref() const {
- auto p = check(curr, "dereference past end");
- return (*p)[curr]; // check成功,返回一個p指針,指向make_shared指向的vector
- } // 解引用,make_shared獲取vector,用下表運算符返回curr位置上的對象
- StrBlobPtr& incr() {
- check(curr, "increment past end of StrBlobPtr");
- ++curr;
- return *this;
- }
- bool operator!=(const StrBlobPtr& p) { return p.curr != curr; }
- private:
- weak_ptr<vector<string>> wptr;
- size_t curr;
- shared_ptr<vector<string>> check(size_t i, const string& msg) const
- {
- auto rent = wptr.lock();
- if (!rent)
- throw runtime_error("unbound StrBlobPtr");
- if (i >= rent->size())
- throw out_of_range(msg);
- return rent;
- }
- };
- StrBlobPtr StrBlob::begin()
- {
- return StrBlobPtr(*this);
- }
- StrBlobPtr StrBlob::end()
- {
- return StrBlobPtr(*this, data->size());
- }
新聞熱點
疑難解答