解析c++ 中智能指針引用計數(shù)為什么不是0原理
問題示例1:
#include<memory>
#include<cstdio>
#include<map>
using namespace std;
int main() {
shared_ptr<int> ptr = make_shared<int>(100);
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
map<int, shared_ptr<int>> mp;
mp.insert(pair<int, shared_ptr<int>>(1, ptr));
mp.insert(pair<int, shared_ptr<int>>(2, ptr));
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
mp.clear();
mp.clear();
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
return 0;
}輸出:
=100,count=1
=100,count=3
=100,count=1 // 為什么這里引用計數(shù)是1而不是0呢?
問題示例2:
#include<memory>
#include<cstdio>
#include<map>
using namespace std;
int main() {
shared_ptr<int> ptr = make_shared<int>(100);
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
map<int, shared_ptr<int>> mp;
mp.insert(pair<int, shared_ptr<int>>(1, ptr));
mp.insert(pair<int, shared_ptr<int>>(2, ptr));
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
ptr.reset();
printf("count=%ld\n", ptr.use_count());
return 0;
}輸出:
=100,count=1
=100,count=3
count=0 //這里為什么是0而不是2呢? 一直理解的 reset()是引用計數(shù)減1.
解析
問題1:
ptr 還在,還有一個引用。
問題2:
reset 之后,ptr 的指向改變,引用計數(shù)已經(jīng)不是原來指針的引用計數(shù)了。新指針是個 nullptr ,引用計數(shù)為 0 。原來的指針引用計數(shù)是 2 ,兩個引用都在 map 里,已經(jīng)無法通過 ptr 訪問。
- 對于問題 1 中的第三次輸出,ptr 沒有釋放,因此還有 1 個引用計數(shù)占用,打印 1.
- 對于問題 2 中的第三次輸出,是 ptr 這個共享指針本身釋放,而非資源釋放,因此 ptr.use_count() 打印 0.
可以運行下面代碼驗證:
#include<memory>
#include<cstdio>
#include<map>
using namespace std;
int main() {
shared_ptr<int> ptr = make_shared<int>(100);
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
map<int, shared_ptr<int>> mp;
mp.insert(pair<int, shared_ptr<int>>(1, ptr));
mp.insert(pair<int, shared_ptr<int>>(2, ptr));
printf("=%d,count=%ld\n", *ptr.get(), ptr.use_count());
ptr.reset();
printf("count=%ld\n", ptr.use_count());
printf("=%d,count=%ld\n", *mp[1].get(), mp[1].use_count());
printf("=%d,count=%ld\n", *mp[2].get(), mp[2].use_count());
return 0;
}輸出:
=100,count=1
=100,count=3
count=0
=100,count=2
=100,count=2
函數(shù)邏輯
你可以設(shè)想一下這個函數(shù)的邏輯
void reset() _NOEXCEPT
{
shared_ptr().swap(*this);
}第一步, 創(chuàng)造一個空shared_ptr對象,與原智能指針交換.交換后指向nullptr,引用為0;
第二步, 原始的指針成了右值, 在語句調(diào)用結(jié)束消滅, 隨即, 原資源引用數(shù)減一, 如減為0, 自行消滅,否則繼續(xù)留存.
以上就是解析C語言中智能指針引用計數(shù)為什么不是0原理的詳細內(nèi)容,更多關(guān)于C語言智能指針引用計數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
OpenCV獲取圖像中直線上的數(shù)據(jù)具體流程
對圖像進行處理時,經(jīng)常會有這類需求:客戶想要提取出圖像中某條直線或者ROI區(qū)域內(nèi)的感興趣數(shù)據(jù),進行重點關(guān)注,怎么操作呢,下面小編通過實例代碼介紹下OpenCV獲取圖像中直線上的數(shù)據(jù),一起看看吧2021-11-11
C語言中獲取文件狀態(tài)的相關(guān)函數(shù)小結(jié)
這篇文章主要介紹了C語言中獲取文件狀態(tài)的相關(guān)函數(shù)小結(jié),包括stat()函數(shù)和fstat()函數(shù)以及l(fā)stat()函數(shù)的使用,需要的朋友可以參考下2015-09-09
C++流程控制中用于跳轉(zhuǎn)的return和goto語句學習教程
這篇文章主要介紹了C++流程控制中用于跳轉(zhuǎn)的return和goto語句學習教程,是C++入門學習中的基礎(chǔ)知識,需要的朋友可以參考下2016-01-01

