網站首頁 編程語言 正文
一、內存泄漏-永恒的話題
- 動態申請堆空間,用完后不歸還
- C++ 語言中沒有垃圾回收的機制
- 指針無法控制所指堆空間的生命周期
下面看一段內存泄漏的代碼:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
this->i = i;
}
int value()
{
return i;
}
~Test()
{
}
};
int main()
{
for(int i=0; i<5; i++)
{
Test* p = new Test(i);
cout << p->value() << endl;
}
return 0;
}
輸出結果如下:
二、深度思考
- 需要一個特殊的指針
- 指針生命周期結束時主動釋放堆空間
- 一片堆空間最多只能由一個指針標識
- 杜絕指針運算和指針比較
三、智能指針分析
解決方案
- 重載指針特征操作符( -> 和 * )
- 只能通過類的成員函數重載
- 重載函數不能使用參數
- 只能定義一個重載函數
下面看一段智能指針的使用示例:
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
cout << "Test(int i)" << endl;
this->i = i;
}
int value()
{
return i;
}
~Test()
{
cout << "~Test()" << endl;
}
};
class Pointer
{
Test* mp;
public:
Pointer(Test* p = NULL)
{
mp = p;
}
Pointer(const Pointer& obj)
{
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
Pointer& operator = (const Pointer& obj)
{
if (this != &obj)
{
delete mp;
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
return *this;
}
Test* operator -> ()
{
return mp;
}
Test& operator * ()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
~Pointer()
{
delete mp;
}
};
int main()
{
Pointer p1 = new Test(0);
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNull() << endl;
cout << p2->value() << endl;
return 0;
}
輸出結果如下:
注意這兩行代碼的含義,
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
表明當前對象的成員指針指向初始化對象的成員指針所對應的堆空間,這就兩個智能指針對象指向了同一片堆空間,然后 const_cast<Pointer&>(obj).mp = NULL; 表明初始化對象把自己管理的堆空間交給當前對象。這就完成了前面說的“一片堆空間最多只能由一個指針標識”。
智能指針使用的軍規:只能用來指向堆空間中的對象或者變量
四、小結
- 指針特征操作符( -> 和 * )可以被重載
- 重載指針特征符能夠使用對象代替指針
- 智能指針只能用于指向堆空間中的內存
- 智能指針的意義在于最大程度的避免內存問題
原文鏈接:https://blog.csdn.net/weixin_43129713/article/details/124513911
相關推薦
- 2022-07-02 less,sass,scss的關系與區別
- 2022-05-28 C#調用WebService的方法介紹_C#教程
- 2022-04-27 Quarkus集成redis操作Redisson實現數據互通_Redis
- 2022-07-11 UVM中UVM_ERROR到達一定數量后結束
- 2022-08-21 python數字圖像處理之基本形態學濾波_python
- 2022-04-09 詳解Docker下nginx外掛配置和文件_docker
- 2022-05-06 Redis定時任務原理的實現_Redis
- 2023-06-21 詳解C++17中nodiscard標記符的使用_C 語言
- 最近更新
-
- 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同步修改后的遠程分支