c/c++ 智能指針 unique_ptr 使用
阿新 • • 發佈:2018-09-28
而不是 eve reset str work table tab cout com
智能指針 unique_ptr 使用
和shared_ptr不同,可以有多個shared_ptr指向同一個內存,只能有1個unique_ptr指向某個內存。因此unique_ptr不支持普通的拷貝和賦值。
一,先來個表格,嘮嘮unique_ptr
操作 | 功能描述 |
---|---|
unique_ptr<T> u(q) | 智能指針u管理內置指針q所指向的對象;q必須指向new分配的內存,且能夠轉換為T*。 |
unique_ptr<T, D> u(u, d) | 用類型為D的對象d來代替delete |
u = nullptr | 釋放u指向的對象,並將u置為空 |
u.release() | u放棄對指針的控制權,返回內置指針,並將u置為空 |
u.reset() | 釋放u所指向的對象,並將u置為空。 |
u.reset(q) | 如果還傳遞了參數q,讓u指向q |
u.reset(q, d) | 如果還傳遞了參數d,將會調用d,而不是delete來釋放q |
小例子索引
代碼塊 | 功能描述 |
---|---|
test1 | 不可以拷貝和賦值 |
test2 | 自定義刪除器 |
test3 | reset和release的使用 |
test4 | unique_ptr作為函數的返回值 |
小例子
include <iostream> #include <memory> #include <vector> using namespace std; class Test{ public: Test(int d = 0) : data(d){cout << "new" << data << endl;} ~Test(){cout << "del" << data << endl;} private: int data; }; void my_deleter(Test* t){ cout << "worked" << endl; } unique_ptr<int> cl1(int p){ return unique_ptr<int>(new int(p)); } unique_ptr<int> cl2(int p){ unique_ptr<int> rt(new int(p)); return rt; } void fl1(unique_ptr<int> p){ *p = 100; } int main(){ //test1 不可以拷貝和賦值 /* unique_ptr<int> p1(new int(11)); //unique_ptr<int> p2(p1);//NG unique_ptr<int> p3(new int(10)); //p3 = p1;//NG */ //test2 自定義刪除器 //不再調用Test的析構函數了 //unique_ptr<Test, decltype(my_deleter)*> u(new Test(1), my_deleter); //test3 reset和release的使用 /* unique_ptr<Test> p1(new Test(1)); unique_ptr<Test> p2(p1.release());//將p1置為空,p2指向了原來p1指向的對象 unique_ptr<Test> p3(new Test(3)); p2.reset(p3.release());//先釋放了p2所指向的內存,讓p2指向了原來p3指向的對象,p3被置為空 p2.release();//錯誤,p2不會釋放內存,而且丟失了能夠釋放內存的指針 auto p = p2.release();//正確,但必須要記得delete(p) */ //test4 unique_ptr作為函數的返回值 /* unique_ptr<int> p1 = cl1(11); cout << *p1 << endl; unique_ptr<int> p2 = cl2(22); cout << *p2 << endl; //fl1(p2);//NG 編譯不過 */ }
github完整代碼
c/c++ 學習互助QQ群:877684253
本人微信:xiaoshitou5854
c/c++ 智能指針 unique_ptr 使用