C++特性之智能指針shared_ptr詳解
shared_ptr 是C++11提供的一種智能指針類,它足夠智能,可以在任何地方都不使用時自動刪除相關(guān)指針,從而幫助徹底消除內(nèi)存泄漏和懸空指針的問題。
它遵循共享所有權(quán)的概念,即不同的 shared_ptr 對象可以與相同的指針相關(guān)聯(lián),并在內(nèi)部使用引用計數(shù)機制來實現(xiàn)這一點。
每個 shared_ptr 對象在內(nèi)部指向兩個內(nèi)存位置:
1、指向?qū)ο蟮闹羔槨?/p>
2、用于控制引用計數(shù)數(shù)據(jù)的指針。
共享所有權(quán)如何在參考計數(shù)的幫助下工作:
1、當(dāng)新的 shared_ptr 對象與指針關(guān)聯(lián)時,則在其構(gòu)造函數(shù)中,將與此指針關(guān)聯(lián)的引用計數(shù)增加1。
2、當(dāng)任何 shared_ptr 對象超出作用域時,則在其析構(gòu)函數(shù)中,它將關(guān)聯(lián)指針的引用計數(shù)減1。如果引用計數(shù)變?yōu)?,則表示沒有其他 shared_ptr 對象與此內(nèi)存關(guān)聯(lián),在這種情況下,它使用delete函數(shù)刪除該內(nèi)存。
1.創(chuàng)建指針對象
使用原始指針創(chuàng)建 shared_ptr 對象
std::shared_ptr<int> p1(new int()); ???????//檢查shared_ptr對象的引用計數(shù) p1.use_count();
上面這行代碼在堆上創(chuàng)建了兩塊內(nèi)存:1:存儲int。2:用于引用計數(shù)的內(nèi)存,管理附加此內(nèi)存的 shared_ptr 對象的計數(shù),最初計數(shù)將為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;//默認構(gòu)造,沒有獲取任何指針的所有權(quán),引用計數(shù)為0
std::shared_ptr<int> p2 (nullptr);//同1
std::shared_ptr<int> p3 (new int);//擁有指向int的指針所有權(quán),引用計數(shù)為1
std::shared_ptr<int> p4 (new int, deleter);//作用同3,但是擁有自己的析構(gòu)方法,如果指針所指向?qū)ο鬄閺?fù)雜結(jié)構(gòu)C
//結(jié)構(gòu)C里有指針,默認析構(gòu)函數(shù)不會將結(jié)構(gòu)C里的指針data所指向的內(nèi)存釋放,這時需要自己使用自己的析構(gòu)函數(shù)(刪除器)
std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());//同4,但擁有自己的分配器(構(gòu)造函數(shù)),如成員中有指針,可以為指針分配內(nèi)存,原理跟淺拷貝和深拷貝類似
std::shared_ptr<int> p6 (p5);//如果p5引用計數(shù)不為0,則引用計數(shù)加1,否則同樣為0
std::shared_ptr<int> p7 (std::move(p6));//獲取p6的引用計數(shù),p6引用計數(shù)為0
std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));//p8獲取所有權(quán),引用計數(shù)設(shè)置為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 對象,因為帶有參數(shù)的 shared_ptr 構(gòu)造函數(shù)是 explicit 類型的,所以不能像這樣std::shared_ptr<int> p1 = new int();隱式調(diào)用它構(gòu)造函數(shù)。創(chuàng)建新的shared_ptr對象的最佳方法是使用std :: make_shared:
std::shared_ptr<int> p1 = std::make_shared<int>();
std::make_shared 一次性為int對象和用于引用計數(shù)的數(shù)據(jù)都分配了內(nèi)存,而new操作符只是為int分配了內(nèi)存。
賦值:
#include <iostream>
#include <memory>
int main () {
std::shared_ptr<int> foo;
std::shared_ptr<int> bar (new int(10));
foo = bar; // 拷貝,引用計數(shù)加1
bar = std::make_shared<int> (20); // 移動
//unique_ptr 不共享它的指針。它無法復(fù)制到其他 unique_ptr,無法通過值傳遞到函數(shù),也無法用于需要副本的任何標準模板庫 (STL) 算法。只能移動unique_ptr
std::unique_ptr<int> unique (new int(30));
foo = std::move(unique); // move from unique_ptr,引用計數(shù)轉(zhuǎn)移
std::cout << "*foo: " << *foo << '\n';
std::cout << "*bar: " << *bar << '\n';
return 0;
}
Output:
/*
*foo: 30
*bar: 20
*/
2.分離關(guān)聯(lián)的原始指針
要使 shared_ptr 對象取消與相關(guān)指針的關(guān)聯(lián),可以使用reset()函數(shù):
//不帶參數(shù)的reset(),將引用計數(shù)減少1,如果引用計數(shù)變?yōu)?,則刪除指針 p1.reset(); //帶參數(shù)的reset(),他將內(nèi)部指向新指針,因此其引用計數(shù)將再次變?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
// 打印引用個數(shù):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;
// 無參數(shù)調(diào)用reset,無關(guān)聯(lián)指針,引用個數(shù)為0
p1.reset();
std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
// 帶參數(shù)調(diào)用reset,引用個數(shù)為1
p1.reset(new int(11));
std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
// 把對象重置為NULL,引用計數(shù)為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檢測
當(dāng)我們創(chuàng)建 shared_ptr 對象而不分配任何值時,它就是空的;普通指針不分配空間的時候相當(dāng)于一個野指針,指向垃圾空間,且無法判斷指向的是否是有用數(shù)據(jù)。
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;
到此這篇關(guān)于C++特性之智能指針shared_ptr詳解的文章就介紹到這了,更多相關(guān)C++智能指針shared_ptr內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++ Boost shared_ptr共享指針詳細講解
- C++簡單實現(xiàn)shared_ptr的代碼
- C++中Boost的智能指針shared_ptr
- C++智能指針之shared_ptr的具體使用
- C++智能指針之shared_ptr詳解
- C++智能指針shared_ptr
- C++11中的智能指針shared_ptr、weak_ptr源碼解析
- 深入學(xué)習(xí)C++智能指針之shared_ptr與右值引用的方法
- C++11 std::shared_ptr總結(jié)與使用示例代碼詳解
- C++11 智能指針之shared_ptr代碼詳解
- C++共享智能指針shared_ptr的實現(xiàn)
相關(guān)文章
C語言中枚舉與聯(lián)合體的使用方法(enum union)
枚舉的意思就是列舉,將每一個可能的取值都進行一一列舉,下面這篇文章主要給大家介紹了關(guān)于C語言中枚舉與聯(lián)合體的使用方法,需要的朋友可以參考下2021-09-09
用C語言求冪函數(shù)和指數(shù)函數(shù)的方法
這篇文章主要介紹了用C語言求冪函數(shù)和指數(shù)函數(shù)的方法,即pow()函數(shù)和sqrt()函數(shù)的使用,需要的朋友可以參考下2015-08-08

