網(wǎng)站首頁 編程語言 正文
shared_ptr 是C++11提供的一種智能指針類,它足夠智能,可以在任何地方都不使用時自動刪除相關指針,從而幫助徹底消除內(nèi)存泄漏和懸空指針的問題。
它遵循共享所有權的概念,即不同的 shared_ptr 對象可以與相同的指針相關聯(lián),并在內(nèi)部使用引用計數(shù)機制來實現(xiàn)這一點。
每個 shared_ptr 對象在內(nèi)部指向兩個內(nèi)存位置:
1、指向?qū)ο蟮闹羔槨?/p>
2、用于控制引用計數(shù)數(shù)據(jù)的指針。
共享所有權如何在參考計數(shù)的幫助下工作:
1、當新的 shared_ptr 對象與指針關聯(lián)時,則在其構造函數(shù)中,將與此指針關聯(lián)的引用計數(shù)增加1。
2、當任何 shared_ptr 對象超出作用域時,則在其析構函數(shù)中,它將關聯(lián)指針的引用計數(shù)減1。如果引用計數(shù)變?yōu)?,則表示沒有其他 shared_ptr 對象與此內(nèi)存關聯(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;//默認構造,沒有獲取任何指針的所有權,引用計數(shù)為0
std::shared_ptr<int> p2 (nullptr);//同1
std::shared_ptr<int> p3 (new int);//擁有指向int的指針所有權,引用計數(shù)為1
std::shared_ptr<int> p4 (new int, deleter);//作用同3,但是擁有自己的析構方法,如果指針所指向?qū)ο鬄閺碗s結構C
//結構C里有指針,默認析構函數(shù)不會將結構C里的指針data所指向的內(nèi)存釋放,這時需要自己使用自己的析構函數(shù)(刪除器)
std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());//同4,但擁有自己的分配器(構造函數(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獲取所有權,引用計數(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 構造函數(shù)是 explicit 類型的,所以不能像這樣std::shared_ptr<int> p1 = new int();隱式調(diào)用它構造函數(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 不共享它的指針。它無法復制到其他 unique_ptr,無法通過值傳遞到函數(shù),也無法用于需要副本的任何標準模板庫 (STL) 算法。只能移動unique_ptr
std::unique_ptr<int> unique (new int(30));
foo = std::move(unique); // move from unique_ptr,引用計數(shù)轉移
std::cout << "*foo: " << *foo << '\n';
std::cout << "*bar: " << *bar << '\n';
return 0;
}
Output:
/*
*foo: 30
*bar: 20
*/
2.分離關聯(lián)的原始指針
要使 shared_ptr 對象取消與相關指針的關聯(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,無關聯(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檢測
當我們創(chuàng)建 shared_ptr 對象而不分配任何值時,它就是空的;普通指針不分配空間的時候相當于一個野指針,指向垃圾空間,且無法判斷指向的是否是有用數(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;
原文鏈接:https://blog.csdn.net/yohnyang/article/details/128118719
相關推薦
- 2022-08-23 Django配合python進行requests請求的問題及解決方法_python
- 2022-04-25 C#使用Npoi導出Excel并合并行列_C#教程
- 2022-08-19 WPF使用DrawingContext實現(xiàn)二維繪圖_C#教程
- 2022-06-12 Python多線程的使用詳情_python
- 2022-08-17 React自定義hook的方法_React
- 2023-12-14 【datetime模塊】將時間加一秒或者減一秒
- 2024-02-27 credentials to a set of origins, list them explici
- 2022-08-05 雪花算法工具類
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支