網站首頁 編程語言 正文
shared_ptr 是C++11提供的一種智能指針類,它足夠智能,可以在任何地方都不使用時自動刪除相關指針,從而幫助徹底消除內存泄漏和懸空指針的問題。
它遵循共享所有權的概念,即不同的 shared_ptr 對象可以與相同的指針相關聯,并在內部使用引用計數機制來實現這一點。
每個 shared_ptr 對象在內部指向兩個內存位置:
1、指向對象的指針。
2、用于控制引用計數數據的指針。
共享所有權如何在參考計數的幫助下工作:
1、當新的 shared_ptr 對象與指針關聯時,則在其構造函數中,將與此指針關聯的引用計數增加1。
2、當任何 shared_ptr 對象超出作用域時,則在其析構函數中,它將關聯指針的引用計數減1。如果引用計數變為0,則表示沒有其他 shared_ptr 對象與此內存關聯,在這種情況下,它使用delete函數刪除該內存。
1.創建指針對象
使用原始指針創建 shared_ptr 對象
std::shared_ptr<int> p1(new int());
???????//檢查shared_ptr對象的引用計數
p1.use_count();
上面這行代碼在堆上創建了兩塊內存: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
*/
創建空的 shared_ptr 對象,因為帶有參數的 shared_ptr 構造函數是 explicit 類型的,所以不能像這樣std::shared_ptr<int> p1 = new int();隱式調用它構造函數。創建新的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,如果引用計數變為0,則刪除指針
p1.reset();
//帶參數的reset(),他將內部指向新指針,因此其引用計數將再次變為1
p1.reset(new int(34));
//使用nullptr重置:
p1=nullptr
#include <iostream>
#include <memory> // 需要包含這個頭文件
int main()
{
// 使用 make_shared 創建空對象
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檢測
當我們創建 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;
原文鏈接:https://blog.csdn.net/yohnyang/article/details/128118719
相關推薦
- 2022-06-25 Python多行輸入程序實例代碼及擴展_python
- 2021-11-06 C/C++?Qt?StringListModel?字符串列表映射組件詳解_C 語言
- 2023-10-09 如何搭建小程序項目,uniApp搭建,uView組件庫的引入和請求配置
- 2022-07-28 C++中操作符的前置與后置有什么區別_C 語言
- 2022-12-23 C++類中如何使用定義的類型別名_C 語言
- 2023-10-26 解決問題:NODE_ENV 不是內部或外部命令,也不是可運行的程序,或者批處理文件
- 2022-07-22 yaml文件的加載使用
- 2022-07-22 CSS3:盒陰影、邊界圖片、指定每一個圓角、背景、過度、動畫、
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支