讀《c++ stragegies and tacitics》的時候看到了一段很nb的**,是關於智慧型指標的 (程式稍作修改,以便在編譯器上執行):
1 #include2using
namespace
std;34
class
string_ptr
9string* operator ->() const
10operator
string*() const
11};
1213
intmain()
類string_ptr是乙個只能指標,用來控制對其所負責的string的訪問。其中定義了兩個函式 operator->()(用來對string成員函式的訪問)和operator string*()(用來進行隱式型別轉換的函式)。
我最大的疑問就是為什麼operator string*()函式沒有返回值(返回值應該為 string *)?如果函式宣告改寫為:
string* operatorstring *() const ;
重新編譯就會出錯 error: return type specified for 'operator std::string* 。原來在operator std::string* ()宣告中就已經指定了返回值型別。
注意sp的初始化也很不一般:「string_ptr sp=&s;」呼叫的是string_ptr的建構函式,而不是複製建構函式。
使用模板來實現該智慧型指標:
1 #include2using
namespace
std;
34 template
5class
ptr
10 t* operator ->() const
11operator t*() const
12};
1314
intmain()
關於C 智慧型指標
普通指標到智慧型指標的轉換 int iptr new int 42 shared ptrp iptr 智慧型指標到普通指標的轉換 int pi p.get 注意的地方 那就是不要將智慧型指標與普通指標混用。如果專案允許,堅持使用智慧型指標,避免原生指標。智慧型指標與普通指標需要特別特別特別的小心翼翼...
關於智慧型指標auto ptr
智慧型指標auto ptr和shared ptr也是面試中經常被問到的乙個 感覺看auto ptr的原始碼反而更加容易理解一些,因為原始碼的 量並不大,而且比較容易理解。本篇主要介紹auto ptr 其特點如下 1.首先auto ptr智慧型指標是個封裝好的類 2.是採用棧上的指標去管理堆上的內容,...
智慧型指標 強弱智慧型指標
在平時編寫 的時候經常會用到new來開闢空間,而我們開闢出來的空間必須得手動去delete他,但是如果程式設計師忘記去手動釋放那邊會出現乙個麻煩的問題,記憶體洩漏!或者是一塊記憶體被多個函式同時使用時,如果其中乙個函式不知道還有其他人也在使用這塊記憶體而釋放掉的話同樣也會引起程式的崩潰。引起記憶體洩...