C++特性之智能指針shared_ptr詳解
shared_ptr 是C++11提供的一種智能指針類,它足夠智能,可以在任何地方都不使用時自動刪除相關指針,從而幫助徹底消除內存泄漏和懸空指針的問題。
它遵循共享所有權的概念,即不同的 shared_ptr 對象可以與相同的指針相關聯,并在內部使用引用計數機制來實現這一點。
每個 shared_ptr 對象在內部指向兩個內存位置:
1、指向對象的指針。
2、用于控制引用計數數據的指針。
共享所有權如何在參考計數的幫助下工作:
1、當新的 shared_ptr 對象與指針關聯時,則在其構造函數中,將與此指針關聯的引用計數增加1。
2、當任何 shared_ptr 對象超出作用域時,則在其析構函數中,它將關聯指針的引用計數減1。如果引用計數變?yōu)?,則表示沒有其他 shared_ptr 對象與此內存關聯,在這種情況下,它使用delete函數刪除該內存。
1.創(chuàng)建指針對象
使用原始指針創(chuàng)建 shared_ptr 對象
std::shared_ptr<int> p1(new int()); ???????//檢查shared_ptr對象的引用計數 p1.use_count();
上面這行代碼在堆上創(chuàng)建了兩塊內存:1:存儲int。2:用于引用計數的內存,管理附加此內存的 shared_ptr 對象的計數,最初計數將為1。
for ex:
#include <iostream> #include <memory> struct C {int* data;}; int main () { auto deleter = [](int*p){ std::cout << "[deleter called]\n"; delete p; };//Labmbda表達式 std::shared_ptr<int> p1;//默認構造,沒有獲取任何指針的所有權,引用計數為0 std::shared_ptr<int> p2 (nullptr);//同1 std::shared_ptr<int> p3 (new int);//擁有指向int的指針所有權,引用計數為1 std::shared_ptr<int> p4 (new int, deleter);//作用同3,但是擁有自己的析構方法,如果指針所指向對象為復雜結構C //結構C里有指針,默認析構函數不會將結構C里的指針data所指向的內存釋放,這時需要自己使用自己的析構函數(刪除器) std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());//同4,但擁有自己的分配器(構造函數),如成員中有指針,可以為指針分配內存,原理跟淺拷貝和深拷貝類似 std::shared_ptr<int> p6 (p5);//如果p5引用計數不為0,則引用計數加1,否則同樣為0 std::shared_ptr<int> p7 (std::move(p6));//獲取p6的引用計數,p6引用計數為0 std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));//p8獲取所有權,引用計數設置為1 std::shared_ptr<C> obj (new C); std::shared_ptr<int> p9 (obj, obj->data);//同6一樣,只不過擁有自己的刪除器與4一樣 std::cout << "use_count:\n"; std::cout << "p1: " << p1.use_count() << '\n'; std::cout << "p2: " << p2.use_count() << '\n'; std::cout << "p3: " << p3.use_count() << '\n'; std::cout << "p4: " << p4.use_count() << '\n'; std::cout << "p5: " << p5.use_count() << '\n'; std::cout << "p6: " << p6.use_count() << '\n'; std::cout << "p7: " << p7.use_count() << '\n'; std::cout << "p8: " << p8.use_count() << '\n'; std::cout << "p9: " << p9.use_count() << '\n'; return 0; } /* Output: use_count: p1: 0 p2: 0 p3: 1 p4: 1 p5: 2 p6: 0 p7: 2 p8: 1 p9: 2 */
創(chuàng)建空的 shared_ptr 對象,因為帶有參數的 shared_ptr 構造函數是 explicit 類型的,所以不能像這樣std::shared_ptr<int> p1 = new int();隱式調用它構造函數。創(chuàng)建新的shared_ptr對象的最佳方法是使用std :: make_shared:
std::shared_ptr<int> p1 = std::make_shared<int>();
std::make_shared 一次性為int對象和用于引用計數的數據都分配了內存,而new操作符只是為int分配了內存。
賦值:
#include <iostream> #include <memory> int main () { std::shared_ptr<int> foo; std::shared_ptr<int> bar (new int(10)); foo = bar; // 拷貝,引用計數加1 bar = std::make_shared<int> (20); // 移動 //unique_ptr 不共享它的指針。它無法復制到其他 unique_ptr,無法通過值傳遞到函數,也無法用于需要副本的任何標準模板庫 (STL) 算法。只能移動unique_ptr std::unique_ptr<int> unique (new int(30)); foo = std::move(unique); // move from unique_ptr,引用計數轉移 std::cout << "*foo: " << *foo << '\n'; std::cout << "*bar: " << *bar << '\n'; return 0; } Output: /* *foo: 30 *bar: 20 */
2.分離關聯的原始指針
要使 shared_ptr 對象取消與相關指針的關聯,可以使用reset()函數:
//不帶參數的reset(),將引用計數減少1,如果引用計數變?yōu)?,則刪除指針 p1.reset(); //帶參數的reset(),他將內部指向新指針,因此其引用計數將再次變?yōu)? p1.reset(new int(34)); //使用nullptr重置: p1=nullptr
#include <iostream> #include <memory> // 需要包含這個頭文件 int main() { // 使用 make_shared 創(chuàng)建空對象 std::shared_ptr<int> p1 = std::make_shared<int>(); *p1 = 78; std::cout << "p1 = " << *p1 << std::endl; // 輸出78 // 打印引用個數:1 std::cout << "p1 Reference count = " << p1.use_count() << std::endl; // 第2個 shared_ptr 對象指向同一個指針 std::shared_ptr<int> p2(p1); // 下面兩個輸出都是:2 std::cout << "p2 Reference count = " << p2.use_count() << std::endl; std::cout << "p1 Reference count = " << p1.use_count() << std::endl; // 比較智能指針,p1 等于 p2 if (p1 == p2) { std::cout << "p1 and p2 are pointing to same pointer\n"; } std::cout<<"Reset p1 "<<std::endl; // 無參數調用reset,無關聯指針,引用個數為0 p1.reset(); std::cout << "p1 Reference Count = " << p1.use_count() << std::endl; // 帶參數調用reset,引用個數為1 p1.reset(new int(11)); std::cout << "p1 Reference Count = " << p1.use_count() << std::endl; // 把對象重置為NULL,引用計數為0 p1 = nullptr; std::cout << "p1 Reference Count = " << p1.use_count() << std::endl; if (!p1) { std::cout << "p1 is NULL" << std::endl; // 輸出 } return 0; }
3.與普通指針比較
缺少 ++, – – 和 [] 運算符
與普通指針相比,shared_ptr僅提供-> 、*和==運算符,沒有+、-、++、–、[]等運算符。
#include<iostream> #include<memory> struct Sample { void dummyFunction() { std::cout << "dummyFunction" << std::endl; } }; int main() { std::shared_ptr<Sample> ptr = std::make_shared<Sample>(); (*ptr).dummyFunction(); // 正常 ptr->dummyFunction(); // 正常 // ptr[0]->dummyFunction(); // 錯誤方式 // ptr++; // 錯誤方式 //ptr--; // 錯誤方式 std::shared_ptr<Sample> ptr2(ptr); if (ptr == ptr2) // 正常 std::cout << "ptr and ptr2 are equal" << std::endl; return 0; }
4.NULL檢測
當我們創(chuàng)建 shared_ptr 對象而不分配任何值時,它就是空的;普通指針不分配空間的時候相當于一個野指針,指向垃圾空間,且無法判斷指向的是否是有用數據。
std::shared_ptr<Sample> ptr3; if(!ptr3) std::cout<<"Yes, ptr3 is empty" << std::endl; if(ptr3 == NULL) std::cout<<"ptr3 is empty" << std::endl; if(ptr3 == nullptr) std::cout<<"ptr3 is empty" << std::endl;
到此這篇關于C++特性之智能指針shared_ptr詳解的文章就介紹到這了,更多相關C++智能指針shared_ptr內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!