【C++】智能指針詳解

智能指針:將對內存的管理交付給對象,當對象析構時就能夠清理資源,有效的避免內存泄露問題。(因爲原生態指針(T*)管理資源時,若用戶忘記釋放內存,則可能會導致資源泄露。)

  • 下面介紹四種智能指針
  • 頭文件均爲#include< memory>

一.auto_ptr智能指針

  • C++98中經歷過兩次版本更新。
  • C++11中保留第一版auto_ptr。

1.首先介紹智能指針的三大結構

  • 1.RAII:利用對象生命週期來控制內存資源,構造時獲取資源,析構時釋放資源。
    特點:不需要顯式釋放資源。對象所需資源在其生命週期內始終有效。
  • 2.重載運算符 * (解引用) ->
  • 3.拷貝構造方法/重載=運算符方法,所產生的淺拷貝問題。

2.auto_ptr第一版本模擬實現
解決淺拷貝:通過資源轉移的方法,一份資源只能由一個指針管理。之前的指針設置爲空。

#include<iostream>
using namespace std;
template <class T>
class auto_ptr1 {
public:
//1.RAII:
	auto_ptr1(T* ptr=nullptr)
		:_ptr(ptr)
	{}
	//2.重載* -> 運算符
	T& operator *() {
		return *_ptr;
	}
	T& operator ->() {
		return _ptr;
	}
	//3.拷貝構造  並用資源轉移的方法解決淺拷貝
	auto_ptr1(auto_ptr1<T>& ap) 
		:_ptr(ap._ptr)
	{
		ap._ptr = nullptr;
	}
	auto_ptr1<T>& operator =(auto_ptr1<T>& ap) {
		if (this != &ap) {
			if (_ptr) {
				delete _ptr;
			}
			_ptr = ap._ptr;
			ap._ptr = nullptr;
		}
		_ptr = ap._ptr;
		ap._ptr = nullptr;
	}
	~auto_ptr1() {
		if (_ptr){
			delete _ptr;
			_ptr = nullptr;
		}
	}
private:
	T* _ptr;
};
int main() {
	auto_ptr<int> ap1(new int);
	*ap1 = 10;
	auto_ptr<int> ap2(ap1);
	*ap2 = 20;
	auto_ptr<int> ap3(new int);
	*ap3 = 30;
	auto_ptr<int> ap4;
	ap4 = ap3;
	*ap4 = 40;
	return 0;
}

在這裏插入圖片描述
2.auto_ptr第二版本模擬實現
解決淺拷貝:通過資源管理權限的方法,設置一個bool類型變量,只有最後一個指針爲true,擁有可以釋放資源的權利。

#include<iostream>
#include<Windows.h>
using namespace std;
template <class T>
class auto_ptr1 {
public:
	auto_ptr1(T* ptr=nullptr)
		:_ptr(ptr)
		,_owner(false)
	{
		if (_ptr) {
			_owner = true;
		}
	}
	T& operator *() {
		return *_ptr;
	}
	T& operator ->() {
		return _ptr;
	}
	auto_ptr1(auto_ptr1<T>& ap) 
		:_ptr(ap._ptr)
		,_owner(ap._owner)
	{
		ap._owner = false;
	}
	auto_ptr1<T>& operator =(auto_ptr1<T>& ap) {
		if (this != &ap) {
			if (_ptr&&_owner) {
				delete _ptr;
			}
			_ptr = ap._ptr;
			_owner = ap._owner;
			ap._owner = false;
		}
		return *this;
	}
	~auto_ptr1() {
		if (_ptr&&_owner){
			delete _ptr;
			_ptr = nullptr;
		}
	}
private:
	T* _ptr;
	bool _owner;
};
int main() {
	auto_ptr1<int> ap1(new int);
	*ap1 = 10;
	auto_ptr1<int> ap2(ap1);
	*ap2 = 20;
	auto_ptr1<int> ap3(new int);
	*ap3 = 30;
	auto_ptr1<int> ap4;
	ap4 = ap3;
	*ap4 = 40;
	return 0;
}

在這裏插入圖片描述
3.C++11中,auto_ptr恢復到第一版本,因爲上一版本有缺陷(可能成爲野指針)。並提供了更優質的智能指針。

二.unique_ptr智能指針

1.原理:

  • RAII
  • 重載* ->
  • 解決淺拷貝:不允許調用拷貝構造函數以及調用重載=運算符。即不允許進行拷貝。

2.unique_ptr模擬實現

#include<iostream>
using namespace std;
template <class T>
class unique_ptr1 {
public:
	unique_ptr1(T* ptr=nullptr)
		:_ptr(ptr)
	{}
	T& operator *() {
		return *_ptr;
	}
	T& operator ->() {
		return _ptr;
	}
	unique_ptr1(unique_ptr1<T>& ap)=delete   //函數後面添加=delete  表示函數被刪除,不允許被調用。
	{}
	//private :
	//            unique_ptr1(unique_ptr1<T>& ap){}  將函數私有化也可以。
	unique_ptr1<T>& operator =(unique_ptr1<T>& ap) =delete
	{}  
	~unique_ptr1() {
		if (_ptr){
			delete _ptr;
			_ptr = nullptr;
		}
	}
private:
	T* _ptr;
};
int main() {
	unique_ptr1<int> ap1(new int);
	*ap1 = 10;
	return 0;
}

三.shared_ptr智能指針

1.原理

  • RAII
  • 重載* ->
  • 解決淺拷貝:利用引用計數方式(記錄資源被對象使用的個數)

2.代碼

#include<iostream>
using namespace std;
template <class T>
class shared_ptr1 {
public:
	shared_ptr1(T* ptr=nullptr)
		:_ptr(ptr)
		,_pcount(new int)
	{
		if (_ptr)
			*_pcount = 1;
	}
	T& operator *() {
		return *_ptr;
	}
	T& operator ->() {
		return _ptr;
	}
	shared_ptr1(shared_ptr1<T>& ap)
		:_ptr(ap._ptr)
		, _pcount(ap._pcount)
	{
		if (_ptr)
			(*_pcount)++;
	}
	shared_ptr1<T>& operator =(shared_ptr1<T>& ap)
	{
		if (this->_ptr != ap._ptr) {
			if (_ptr&&--*_pcount == 0) {
				delete _ptr;
				_ptr = nullptr;
			}
			_ptr = ap._ptr;
			_pcount = ap._pcount;
			if (_ptr) {
				(*_pcount)++;
			}
	     }
		return *this;
	}
	~shared_ptr1() {
		if (_ptr&&--*_pcount==0){
			delete _ptr;
			_ptr = nullptr;
		}
	}
private:
	T* _ptr;
	int * _pcount;
};
int main() {
	shared_ptr1<int> ap1(new int);
	*ap1 = 10;
	shared_ptr1<int> ap2(ap1);
	*ap2 = 20;
	shared_ptr1<int> ap3(new int);
	*ap3 = 30;
	shared_ptr1<int> ap4(new int);
	ap4 = ap3;
	*ap4 = 40;
	return 0;
}

在這裏插入圖片描述

四.weak_ptr智能指針

1.說明:weak_ptr與shared_ptr原理相同,均採用引用計數的方法解決淺拷貝。但weak_ptr不可以單獨使用,必須配套shared_ptr,爲了解決shared_ptr產生的循環引用(相互引用,互相等待,不能調用析構函數,從而資源泄露)。-------》只需將結構內部循環引用的智能指針替換爲weak_ptr即可。
2.原理:shared_ptr與weak_ptr都有一個獨立的_pcount引用計數。所以可以避免循環引用導致的資源泄露。
3.代碼

#include<iostream>
#include<memory>
using namespace std;
struct ListNode
{
	int _data;
	weak_ptr<ListNode> _prev;
	weak_ptr<ListNode> _next;   //只需將結構內部循環引用的智能指針替換爲weak_ptr即可。
	~ListNode() { cout << "~ListNode()" << endl; }
};
int main()
{
	shared_ptr<ListNode> node1(new ListNode);
	shared_ptr<ListNode> node2(new ListNode);
	node1->_next = node2;
	node2->_prev = node1;
	return 0;
}

五.智能指針注意事項

1.刪除器:析構時,不同的構造方式需要調用不同的析構函數。

template<class T>
struct FreeFunc {
 void operator()(T* ptr)
 {
 free(ptr);
 }
};
template<class T>
struct DeleteArrayFunc {
 void operator()(T* ptr)
 { 
 delete[] ptr; 
 }
}
int main()
{
 FreeFunc<int> freeFunc;
 shared_ptr<int> sp1((int*)malloc(4), freeFunc);
 DeleteArrayFunc<int> deleteArrayFunc;
 shared_ptr<int> sp2((int*)malloc(4), deleteArrayFunc);
 return 0; 
 }

2.線程安全問題:當遇到多線程問題時,資源可能不安全。
解決方法:加鎖以及解鎖。

#include <thread>
#include <mutex>
template <class T>
class SharedPtr
{
public:
 SharedPtr(T* ptr = nullptr)
 : _ptr(ptr)
 , _pRefCount(new int(1))
 , _pMutex(new mutex)
 {}
 ~SharedPtr() {Release();}
 SharedPtr(const SharedPtr<T>& sp)
 : _ptr(sp._ptr)
 , _pRefCount(sp._pRefCount)
 , _pMutex(sp._pMutex)
 {
 AddRefCount();
 }
 // sp1 = sp2
 SharedPtr<T>& operator=(const SharedPtr<T>& sp)
 {
 //if (this != &sp)
 if (_ptr != sp._ptr)
 {
 // 釋放管理的舊資源
 Release();
 // 共享管理新對象的資源,並增加引用計數
 _ptr = sp._ptr;
 _pRefCount = sp._pRefCount;
 _pMutex = sp._pMutex;
 AddRefCount();
 }
 return *this;
 }
 T& operator*() {return *_ptr;}
 T* operator->() {return _ptr;}
 int UseCount() {return *_pRefCount;}
 T* Get() { return _ptr; }
 void AddRefCount()
 {
 // 加鎖或者使用加1的原子操作
 _pMutex->lock();
 ++(*_pRefCount);
 _pMutex->unlock();
 }
private:
 void Release()
 {
 bool deleteflag = false;
 // 引用計數減1,如果減到0,則釋放資源
 _pMutex.lock();
 if (--(*_pRefCount) == 0)
 {
 delete _ptr;
 delete _pRefCount;
 deleteflag = true;
 }
 _pMutex.unlock();
 
 if(deleteflag == true)
 delete _pMutex;
 }
private:
 int* _pRefCount; // 引用計數
 T* _ptr; // 指向管理資源的指針 
 mutex* _pMutex; // 互斥鎖
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章