C++ Primer 5th笔记(chap 12 动态内存)unique_ptr
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(chap 12 动态内存)unique_ptr
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 定義
定義一個unique_ptr時,需要將其綁定到一個new返回的指針上。
unique_ptr p1;
unique_ptr p2(new int(42));
2. unique_ptr 不能進(jìn)行普通的拷貝或者賦值, 不能共享所有權(quán),但是可以將所有權(quán),進(jìn)行轉(zhuǎn)移(調(diào)用 release 或者 reset 來轉(zhuǎn)移指針的所有權(quán))
// transfers ownership from p1 (which points to the string Stegosaurus) to p2 unique_ptr<string> p2(p1.release()); // release makes p1 null unique_ptr<string> p3(new string("Trex")); // transfers ownership from p3 to p2 p2.reset(p3.release()); // reset deletes the memory to which p2 had pointed //特殊的拷貝和賦值int i = 10;unique_ptr<int> testInt = clone(i);unique_ptr<int> static clone(int p){unique_ptr<int>q(new int(p));return q;//return unique<int>q(new int(p));}unique_ptr操作
| unique_ptr u1 | 空unique_ptr,可以指向類型為T的對象,u1會使用delete來釋放它的指針 |
| unique_ptr <T,D> u2 | u2使用一個類型為D的可調(diào)用對象來釋放它的指針 |
| unique_ptr <T,D> u(d) | 空unique_ptr,指向類型為T的對象,用類型為D的對象d代替delete |
| u=nullptr | 釋放u指向的對象,將u置為空 |
| u.release() | u放棄對指針的控制權(quán),返回指針,并將u置為空 |
| u.reset() | 釋放u指針對象 |
| u.reset(q)/u.reset(nullptr) | 如果提供了內(nèi)置指針q,令u指向這個對象;否則將u置為空 |
3. 自定義刪除器
當(dāng) unique_str 被銷毀時,它所指向的對象也會被銷毀。
unique_str 自定義刪除器和上面 shared_str 不同,我們必須在尖括號中 unique_str 指向類型后提供刪除器類型。
eg.
eg2.
typedef int connection;connection* connect(connection* d){cout << "正在連接..." << endl;d = new connection();return d;}void static disconnect(connection* p){cout << "斷開連接..." << endl;}void test_disconnect(){connection* p = new connection(); connection* p2 = connect(p);cout << p << endl;cout << p2 << endl;unique_ptr<connection, decltype(disconnect)*>q(p2, disconnect);//在尖括號中提供類型,圓括號內(nèi)提供尖括號中的類型的對象。//使用decltype()關(guān)鍵字返回一個函數(shù)類型,所以必須添加一個*號來指出我們使用的是一個指針//p.release(); //error:p2不會釋放內(nèi)存,而且丟失了指針//auto q2 = p.release(); //q 是int * 類型, 記得delete釋放q}總結(jié)
以上是生活随笔為你收集整理的C++ Primer 5th笔记(chap 12 动态内存)unique_ptr的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(cha
- 下一篇: C++ Primer 5th笔记(cha