C++之 智能指针


引入

试想一下:

  1. 如果用户malloc申请出来的空间没有进行释放,那就存在内存泄漏的问题。
  2. 再者说异常安全问题。如果在mallocfree之间存在异常抛出,那么还是存在内存泄漏的异常安全问题。

没有内嵌垃圾回收机制的C++,对于它的程序编写人员的要求就十分严苛。那么有没有什么好办法可以智能化管理这些内存呢?有的!这就是今天引入的智能指针,他是RAII思想的一种具像。

RAII

RAII(Resource Acquisition Is Initialization)资源获取即初始化。

它是一种利用对象生命周期来控制程序资源(如内存、文件句柄、网络连接、互斥量等等)的简单技术。

对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。至此我们可以看到实际上就是把一份资源的责任托管给了一个对象

这种做法有两大好处:

  1. 不需要显式释放资源。析构时自动调用。
  2. 采用这种方式,对象所需的资源在其生命期内始终保持有效

使用RAII思想设计的SmartPtr类

template<class T>		//泛型,之后有机会讲解
class SmartPtr {
public:
	SmartPtr(T* ptr = nullptr)
		: _ptr(ptr)
	{}
	~SmartPtr(){
		if (_ptr)
			delete _ptr;
	}
private:
	T* _ptr;
};

void MergeSort(int* a, int n){
	int* tmp = (int*)malloc(sizeof(int)*n);
	
	SmartPtr<int> sp(tmp);	// 将tmp指针委托给了sp对象
}	// 离开作用域,生命周期结束,释放托管资源

int main(){
	try {
		int a[5] = { 4, 5, 2, 3, 1 };
		MergeSort(a, 5);
	}
	catch (const exception& e){
		cout << e.what() << endl;
	}
	return 0;
}

上面这个SmartPtr类已经具有智能指针的雏形了,但还不是一个真正意义上的上智能指针,因为它还不具有指针的行为

指针有两种基本行为:

  1. 解引用*读取内容。
  2. 可以通过->去访问所指空间中的内容。

因此类中还得需要将*->操作符进行重载,才可让其像指针一样去使用。

template<class T>
class SmartPtr{
public:
	//1. RAII
	SmartPtr(T* ptr)
		:_ptr(ptr)
	{}
	
	~SmartPtr(){
		delete _ptr;
	}
	
	//2. 像指针一样使用
	T& operator*(){ return *_ptr; }		//*:返回引用
	T* operator->(){ return _ptr; }		//->:返回指针
	
private:
	T* _ptr;
};

int main(){
	SmartPtr<int> p(new int);
	
	*p = 10;
	p.operator*() = 20;
	
	p->_a1 = 10;	//本应为p->->_a1编译器特殊处理,但为了语法上的可读性,忽略了一个箭头->
	p.operator->()->_a1 = 20;	//本质
	
	return 0;
}

所以智能指针的原理也非常简单明了:

  1. RAII特性
  2. 重载operator*和opertaor->,具有像指针一样的行为。

1. auto_ptr

其实早在C++98版本的库中就提供了auto_ptr的智能指针。但是为什么它没有在现代工程使用中大放异彩呢,原因还是它有坑啊~

所有的智能指针的定义都存放在<memory>头文件中。

  • auto_ptr的实现原理:管理权转移的思想。

  • auto_ptr的坑在于:当对象拷贝或者赋值后,前对象就悬空了。所以很多公司规定了不能使用auto_ptr

#include <memory>

class Date{
public:
	Date() { cout << "Date()" << endl; }
	~Date() { cout << "~Date()" << endl; }
	int _year;
	int _month;
	int _day;
};

int main(){
	auto_ptr<Date> ap(new Date);
	auto_ptr<Date> copy(ap);	//ap 对象悬空
	
	ap->_year = 2018;		//此操作导致程序崩溃
	return 0;
}

底层原理

模拟实现auto_ptr的管理权转移

template<class T>
class AutoPtr{
public:
	AutoPtr(T* ptr = nullptr)
		: _ptr(ptr)
	{}

	~AutoPtr(){
		if (_ptr)
			delete _ptr;
	}

	// 一旦发生拷贝,就将ap中资源转移到当前对象中,然后令ap与其所管理资源断开联系,这样就解决了一块空间被多个对象使用而造成的程序崩溃问题
	AutoPtr(AutoPtr<T>& ap)
		: _ptr(ap._ptr){
		ap._ptr = nullptr;
	}

	AutoPtr<T>& operator=(AutoPtr<T>& ap){
		if (this != &ap){		// 检测是否为自己给自己赋值
			if (_ptr)
				delete _ptr;	// 释放当前对象中资源

			// 转移ap中资源到当前对象中
			_ptr = ap._ptr;
			ap._ptr = nullptr;		//前对象置空
		}
		return *this;
	}

	T& operator*() { return *_ptr; }
	T* operator->() { return _ptr; }
private:
	T* _ptr;
};
int main(){
	AutoPtr<Date> ap(new Date);

	// 底层拷贝之后就把ap对象的指针赋空了,导致ap对象悬空,再通过ap对象访问资源时就会出现问题。
	AutoPtr<Date> copy(ap);
	ap->_year = 2018;		//出错,对空指针进行解引用,非法写入操作
	return 0;
}

这种“卸磨杀驴”式的资源管理方式十分危险,所以还是尽量少用。下面介绍它的改进版:unique_ptr


2. unique_ptr

  • unique_ptr的设计思路非常的粗暴:防拷贝,也就是不让拷贝和赋值
int main(){
	unique_ptr<Date> up(new Date);
	unique_ptr<Date> copy(ap);		//错误
	
	return 0;
}

底层原理

template<class T>
class UniquePtr{
public:
	UniquePtr(T * ptr = nullptr)
		: _ptr(ptr)
	{}

	~UniquePtr(){
		if (_ptr)
			delete _ptr;
	}

	T& operator*() { return *_ptr; }
	T* operator->() { return _ptr; }

private:
	// C++11 <现代> 防拷贝的方式:delete	删除函数
	UniquePtr(UniquePtr<T> const &) = delete;		
	UniquePtr & operator=(UniquePtr<T> const &) = delete;

	// C++98 <老式经典> 防拷贝的方式:只声明不实现 + 声明成私有
	//UniquePtr(UniquePtr<T> const &);
	//UniquePtr & operator=(UniquePtr<T> const &);
	
private:
	T* _ptr;
};

禁止了拷贝构造与赋值,unique_ptr就成了独自管理资源的角色,更加安全。


3. shared_ptr

C++11中开始提供更加靠谱、并支持拷贝shared_ptr。通过引用计数支持智能指针对象的拷贝。

int main(){
	shared_ptr<Date> sp(new Date);
	shared_ptr<Date> copy(sp);

	cout << "ref count:" << sp.use_count() << endl;
	cout << "ref count:" << copy.use_count() << endl;

	return 0;
}

输出结果

Date()			//Date类的构造函数
ref count:1		//引用计数为 1
ref count:2		//又来了一个对象管理资源,引用计数为 2
~Date()			//Date类的构造函数

shared_ptr的原理:
通过引用计数的方式来实现多个shared_ptr对象之间共享资源。
(例如:高中不同科目的一对一老师共同管理一个学生,最后一个老师的课程上完学生就可以下课了~)

  1. shared_ptr在其内部给每个资源都维护了着一份计数,用来记录该份资源被几个对象共享
  2. 在对象被销毁时(也就是析构函数调用),就说明自己不使用该资源了,对象的引用计数减一
  3. 当引用计数减到0,就说明自己是最后一个使用该资源的对象,必须释放该资源。
  4. 如果不是0,就说明除了自己还有其他对象在使用该份资源,不能释放该资源,否则其他对象就成垂悬指针了。

底层原理

#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;		 // 互斥锁
};
int main(){
	SharedPtr<int> sp1(new int(10));
	SharedPtr<int> sp2(sp1);
	*sp2 = 20;

	//sp1与sp2在管理这部分资源,引用计数为2
	cout << sp1.UseCount() << endl;		//2	
	cout << sp2.UseCount() << endl;		//2 

	SharedPtr<int> sp3(new int(10));
	sp2 = sp3;		//sp3赋值给它,释放管理的旧资源,引用计数-1,
	cout << sp1.UseCount() << endl;		//1
	cout << sp2.UseCount() << endl;		//2
	cout << sp3.UseCount() << endl;		//2

	sp1 = sp3;
	cout << sp1.UseCount() << endl;		//3
	cout << sp2.UseCount() << endl;		//3
	cout << sp3.UseCount() << endl;		//3

	system("pause");
	return 0;
}

shared_ptr的线程安全

通过下面的程序我们来测试shared_ptr的线程安全问题。需要注意的是shared_ptr的线程安全分为两方面:

  1. 智能指针对象中引用计数是多个智能指针对象共享的,两个线程中智能指针的引用计数同时++--,并不是原子操作,引用计数原来是1++2次,可能还是2。这样引用计数就错乱了。会导致资源未释放或者程序崩溃的问题。所以只能指针中引用计数++--是需要加锁的,也就是说引用计数的操作是线程安全的。
  2. 智能指针管理的对象存放在上,两个线程中同时去访问,会导致线程安全问题。
void SharePtrFunc(SharedPtr<Date>& sp, size_t n){
	cout << sp.Get() << endl;
	for (size_t i = 0; i < n; ++i){
		// 智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
		SharedPtr<Date> copy(sp);
		// 这里智能指针访问管理的资源,不是线程安全的。
		
		// 	这些值按我们循环控制两个线程++应该为2n次,但是最终看到的结果,并不一定是加了2n
		// 非原子操作++:
		copy->_year++;
		copy->_month++;
		copy->_day++;
	}
}
int main(){
	SharedPtr<Date> p(new Date);
	cout << p.Get() << endl;

	const size_t n = 100;
	thread t1(SharePtrFunc, p, n);
	thread t2(SharePtrFunc, p, n);
	t1.join();
	t2.join();
	cout << p->_year << endl;
	cout << p->_month << endl;
	cout << p->_day << endl;
	return 0;
}
  1. 演示引用计数线程安全问题,就是把AddRefCountSubRefCount中加的锁去掉!
  2. 演示可能不出现线程安全问题,因为线程安全问题是偶现性问题,main函数的n改大一些,基数大了,概率就变大了,就更容易出现线程不安全。
  3. 上面代码我们使用自己实现的SharedPtr演示,是为了方便演示引用计数的线程安全问题,将代码中的SharedPtr换成shared_ptr进行测试,可以验证库的shared_ptr,发现结论是一样的:
    引用计数是线程安全的,但访问管理的资源不是线程安全的】。

shared_ptr的循环引用

struct ListNode{
	int _data;
	shared_ptr<ListNode> _prev;
	shared_ptr<ListNode> _next;

	~ListNode() { cout << "~ListNode()" << endl; }
};
int main(){
	shared_ptr<ListNode> node1(new ListNode);
	shared_ptr<ListNode> node2(new ListNode);

	cout << node1.use_count() << endl;		//1
	cout << node2.use_count() << endl;		//1

	node1->_next = node2;
	node2->_prev = node1;

	cout << node1.use_count() << endl;		//2
	cout << node2.use_count() << endl;		//2

	return 0;
}

分析:

  1. node1node2两个智能指针对象指向两个节点,引用计数变成1,不用手动delete进行释放。
  2. node1_next指向node2node2_prev指向node1,引用计数变成2
  3. node1node2析构,引用计数减到1,但是_next还指向下一个节点、_prev还指向上一个节点。
    也就是说_next析构了,node2就释放了。同样如果_prev析构了,node1就释放了。
  4. 但是_next属于node的成员,node1释放了,_next才会析构,而node1_prev管理,_prev属于node2成员,所以这就叫循环引用,谁也不会释放。
  5. 输出结果里也并没有打印析构函数中的字符串,说明占用了内存没有释放~

解决方案
在引用计数的场景下,把节点中的_prev_next改成weak_ptr就可以了。
原理就是:

node1->_next = node2;
node2->_prev = node1;

发生上述代码情况时,weak_ptr_next_prev不会增加node1node2的引用计数。

4. weak_ptr

代码可以修改为weak_ptr版本:

struct ListNode{
	int _data;
	weak_ptr<ListNode> _prev;
	weak_ptr<ListNode> _next;

	~ListNode() { cout << "~ListNode()" << endl; }
};
int main(){
	shared_ptr<ListNode> node1(new ListNode);
	shared_ptr<ListNode> node2(new ListNode);

	cout << node1.use_count() << endl;
	cout << node2.use_count() << endl;

	node1->_next = node2;
	node2->_prev = node1;

	cout << node1.use_count() << endl;
	cout << node2.use_count() << endl;
	return 0;
}

输出结果:

1
1
1
1

所以使用weak_ptr就解决了shared_ptr的循环引用问题。

  • weak_ptr 是一种不控制对象生命周期的智能指针,,它指向一个 shared_ptr 管理的对象,进行该对象内存管理的是那个强引用的 shared_ptr
  • weak_ptr只是提供了对管理对象的一个访问手段
  • weak_ptr 设计的目的是为配合 shared_ptr 而引入的一种智能指针来协助 shared_ptr 工作, 它只可以从一个 shared_ptr 或另一个weak_ptr对象构造, 它的构造和析构不会引起引用计数的增加或减少
  • weak_ptr是用来解决shared_ptr相互引用时的死锁问题。如果说两个shared_ptr相互引用,那么这两个指针的引用计数永远不可能下降为0,资源永远不会释放。
  • weak_ptr是对对象的一种弱引用,不会增加对象的引用计数,和shared_ptr之间可以相互转化,shared_ptr可以直接赋值给它,它可以通过调用lock函数来获得shared_ptr

那如果内存不是在上申请的,即并非通过new操作符完成的,要如何通过智能指针管理呢?

其实shared_ptr设计了一个删除器来解决这个问题,它的本质是一个仿函数

// 仿函数的删除器
template<class T>
struct FreeFunc {
	void operator()(T* ptr){
		cout << "free:" << ptr << endl;
		free(ptr);
	}
};

template<class T>
struct DeleteArrayFunc {
	void operator()(T* ptr){
		cout << "delete[]" << ptr << endl;
		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;
}

C++11与boost库智能指针

  1. C++ 98 中产生了第一个智能指针auto_ptr.
  2. C++ boost给出了更实用的scoped_ptrshared_ptrweak_ptr
  3. C++ TR1引入了shared_ptr等。不过TR1并不是标准版,没有流行起来。
  4. C++ 11引入了unique_ptrshared_ptrweak_ptr

unique_ptr对应boost库的scoped_ptr。并且这些智能指针的实现原理是参考boost库中的实现)


lock_guard与unique_lock

智能指针是RAII思想的一个具体体现,同时还有一系列包含RAII思想的产品:
例如C++11中的守卫锁lock_guard):防止异常安全导致的死锁问题。具体表现为将锁托管给一个对象进行管理,出了作用域对象要进行析构,守卫锁的析构函数中包含锁的解锁语句,可以很好的处理异常安全带来的死锁问题。
另外还有一个与之类似的unique_lock:区别是unique_lock支持程序员手动加锁与解锁。而lock_guard只负责RAII

以下简单抽象出守卫锁的模拟实现,以便读者理解:

#include <thread>
#include <mutex>

template<class Mutex>
class LockGuard{
public:
	LockGuard(Mutex& mtx)
		:_mutex(mtx){
		_mutex.lock();
	}
	~LockGuard(){
		_mutex.unlock();
	}
	LockGuard(const LockGuard<Mutex>&) = delete;
private:
	// 注意这里必须使用引用,否则锁的就不是一个互斥量对象
	Mutex& _mutex;
};

mutex mtx;
static int n = 0;

void Func(){
	for (size_t i = 0; i < 1000000; ++i){
		LockGuard<mutex> lock(mtx);
		++n;
	}
}
int main(){
	int begin = clock();
	thread t1(Func);
	thread t2(Func);
	t1.join();
	t2.join();
	int end = clock();
	cout << n << endl;
	cout << "cost time:" << end - begin << endl;

	return 0;
}

输出结果

2000000
cost time:2148
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

giturtle

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值