RAII:智能指针

为什么需要智能指针?

下面我们先分析一下下面这段程序有没有什么内存方面的问题?

int div()
{
    int a, b;
    cin >> a >> b;
    if (b == 0)
    {
        throw invalid_argument("除0错误");
    }
    return a / b;
}

void f1()
{
    int* p = new int;
    try
    {
        cout << div() << endl;
    }
    catch (...)
    {
        //这里如果忘记释放空间,就会发生异常安全问题
        //delete p;
        throw;
    }
    //这里如果忘记释放空间,就会发生内存泄漏问题
    //delete p;
}

int main()
{
	try
	{
		f1();
	}
	catch (exception& e)
	{
		cout << e.what() << endl;
	}

	return 0;
}

问题分析:上面的程序分析后我们发现有以下两个问题?

  1. new出来的空间,没有进行释放,存在内存泄漏的问题。
  2. 异常安全问题。如果在 new和 delete之间存在抛异常,那么还是有内存泄漏。这种问题就叫异常安全。

内存泄漏

什么是内存泄漏,内存泄漏的危害
什么是内存泄漏:内存泄漏指因为疏忽或错误造成程序未能释放已经不再使用的内存的情况。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。

内存泄漏的危害:长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务等等,出现内存泄漏会导致响应越来越慢,最终卡死。

void Example()
{
    //1.内存申请了忘记释放
    int* p1 = (int*)malloc(sizeof(int));
    int* p2 = new int;

    //2.异常安全问题
    int* p3 = new int[10];

    Func(); //这里Func函数抛异常导致 delete[] p3未执行,p3没被释放

    delete[] p3;
}

内存泄漏分类

  • 堆内存泄漏(Heap leak)
    堆内存指的是程序执行中依据须要分配通过 malloc / calloc / realloc / new等从堆中分配的一块内存,用完后必须通过调用相应的 free或者 delete删掉。假设程序的设计错误导致这部分内存没有被释放,那么如果这个程序一直运行则以后这部分空间将无法再被使用,就会产生Heap Leak。如果这个程序终止,即进程结束,则在对应的堆上申请的空间会被自动释放。
  • 系统资源泄漏
    指程序使用系统分配的资源,比如套接字、文件描述符、管道等没有使用对应的函数释放掉,导致系统资源的浪费,严重可导致系统效能减少,系统执行不稳定。

如何检测内存泄漏

如何避免内存泄漏

  1. 工程前期良好的设计规范,养成良好的编码规范,申请的内存空间记着匹配的去释放。
  2. 采用RAII思想或者智能指针来管理资源。
  3. 有些公司内部规范使用内部实现的私有内存管理库。这套库自带内存泄漏检测的功能选项。
  4. 出问题了使用内存泄漏工具检测。ps:不过很多工具都不够靠谱,或者收费昂贵。

总结:
内存泄漏非常常见,解决方案分为两种:

  • 事前预防型。如智能指针等。
  • 事后查错型。如内存泄漏检测工具。

智能指针的使用及原理

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

在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。借此,我们实际上把管理一份资源的责任托管给了一个对象。这种做法有两大好处:

  • 不需要显式地释放资源。
  • 采用这种方式,对象所需的资源在其生命期内始终保持有效。
template<class T>
class Smart_Ptr
{
public:
    Smart_Ptr(T* ptr = nullptr)
        : _ptr(ptr)
    {}

    ~Smart_Ptr()
    {
        if (_ptr)
        {
            delete _ptr;
            _ptr = nullptr;
        }
    }
private:
    T* _ptr;
};

int div()
{
    int a, b;
    cin >> a >> b;
    if (b == 0)
    {
        throw invalid_argument("除0错误");
    }
    return a / b;
}

void f1()
{
    //int* p = new int;
    Smart_Ptr<int> sp(new int);  
    try
    {
        cout << div() << endl;
    }
    catch (...)
    {
        throw;
    }
}

int main()
{
	try
	{
		f1();
	}
	catch (exception& e)
	{
		cout << e.what() << endl;
	}

	return 0;
}

智能指针的原理
上述的SmartPtr还不能将其称为智能指针,因为它还不具有指针的行为。指针可以解引用,也可以通过->去访问所指空间中的内容,因此:SmartPtr模板类中还得需要将* 、->重载下,才可让其像指针一样去使用。

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

    ~Smart_Ptr()
    {
        if (_ptr)
        {
            delete _ptr;
            _ptr = nullptr;
        }
    }

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

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

int main()
{
    Smart_Ptr<int> sp(new int);
    *sp = 10;
    return 0;
}

总结一下智能指针的原理:

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

std::auto_ptr
std::auto_ptr文档
C++库中的智能指针都定义在memory这个头文件中。
C++98版本的库中就提供了auto_ptr的智能指针。下面演示的auto_ptr的使用及问题。

#include <iostream>
using namespace std;

class Date
{
public:
    Date()
    {
        cout << "Date()" << endl;
    }

    ~Date()
    {
        cout << "~Date()" << endl;
    }

    int _year;
    int _month;
    int _day;
};

int main()
{
    std::auto_ptr<Date> ap(new Date);
    std::auto_ptr<Date> copy(ap);

    //auto_ptr的问题:当对象拷贝或者赋值后,前面的对象就悬空了
    //C++98中设计的auto_ptr问题是非常明显的,所以实际中很多公司明确规定了不能使用auto_ptr
    //ap->_year = 1900;
    return 0;
}

auto_ptr的实现原理:管理权转移的思想,下面简化模拟实现了一份AutoPtr来了解它的原理:

namespace Auto_Ptr
{
	template<class T>
	class auto_ptr
	{
	public:
		auto_ptr(T* ptr)
			: _ptr(ptr)
		{}

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

		auto_ptr<T>& operator=(auto_ptr<T>& ap)
		{
			if (this != &ap)
			{
				if (_ptr)
				{
					delete _ptr;
				}
				_ptr = ap._ptr;
				ap._ptr = nullptr;		
			}
			return *this;
		}

		~auto_ptr()
		{
			if (_ptr)
			{
				cout << "delete:" << _ptr << endl;
				delete _ptr;
				_ptr = nullptr;			
			}
		}

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

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

	void TestAuto_Ptr()
	{
		auto_ptr<int> ap1(new int);
		auto_ptr<int> ap2(ap1);

		auto_ptr<int> ap3(new int);
		ap3 = ap2;

		//缺陷:ap2 = ap1场景下ap1就悬空了,访问就会报错,如果不熟悉他的特性就会被坑
		//*ap1 = 10;
	}
}

std::unique_ptr
std::unique_ptr文档
C++11中开始提供更靠谱的 unique_ptr

int main()
{
	unique_ptr<Date> up(new Date);

	// unique_ptr的设计思路非常的粗暴-防拷贝,也就是不让拷贝和赋值。
	//unique_ptr<Date> copy(up);
	return 0;
}

unique_ptr的实现原理:简单粗暴的防拷贝,下面简化模拟实现了一份UniquePtr来了解它的原理

namespace Unique_Ptr
{
	template<class T>
	class unique_ptr
	{
	public:
		unique_ptr(T* ptr)
			: _ptr(ptr)
		{}

		//C++11防拷贝
		unique_ptr(unique_ptr<T>& up) = delete;
		unique_ptr<T>& operator=(unique_ptr<T>& up) = delete;

		~unique_ptr()
		{
			if (_ptr)
			{
				cout << "delete:" << _ptr << endl;
				delete _ptr;
				_ptr = nullptr;
			}
		}

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

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

	void TestUnique_Ptr()
	{
		unique_ptr<int> up1(new int);

		//缺陷:如果有需要拷贝的场景,他就没法使用
		//unique_ptr<int> up2(up1);
	}
}

std::shared_ptr
std::shared_ptr文档
C++11中开始提供更靠谱的并且支持拷贝的 shared_ptr

int main()
{
	//shared_ptr通过引用计数支持智能指针对象的拷贝
	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;
}

shared_ptr的原理:是通过引用计数的方式来实现多个shared_ptr对象之间共享资源。

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

下面简化模拟实现了一份SharedPtr来了解它的原理:

namespace Shared_Ptr
{
	template<class T>
	class shared_ptr
	{
	public:
		shared_ptr(T* ptr)
			: _ptr(ptr)
			, _pcount(new int(1))
		{}

		shared_ptr(shared_ptr<T>& sp)
			: _ptr(sp._ptr)
			, _pcount(sp._pcount)
		{
			++(*_pcount);
		}

		shared_ptr<T>& operator=(shared_ptr<T>& sp)
		{
			if (this != &sp)
			{
				if (--(*_pcount) == 0)
				{
					if (_ptr)
					{
						cout << "delete:" << _ptr << endl;
						delete _ptr;
						_ptr = nullptr;
					}
					delete _pcount;
					_pcount = nullptr;
				}

				_ptr = sp._ptr;
				_pcount = sp._pcount;
				++(*_pcount);
			}
			return *this;
		}

		~shared_ptr()
		{
			if (--(*_pcount) == 0)
			{
				if (_ptr)
				{
					cout << "delete:" << _ptr << endl;
					delete _ptr;
					_ptr = nullptr;
				}

				delete _pcount;
				_pcount = nullptr;
			}
		}

		int UsePcount()
		{
			return *_pcount;
		}

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

		T* operator->()
		{
			return _ptr;
		}
	private:
		T* _ptr;
		int* _pcount; //引用计数
	};

	void TestShared_Ptr1()
	{
		shared_ptr<int> sp1(new int);
		shared_ptr<int> sp2(sp1);

		shared_ptr<int> sp3(new int);
		shared_ptr<int> sp4(sp3);
		shared_ptr<int> sp5(sp3);

		sp1 = sp4;
	}
}

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

  1. 智能指针对象中引用计数是多个智能指针对象共享的,两个线程中智能指针的引用计数同时++或–,这个操作不是原子的,引用计数原来是1,++了两次,可能还是2.这样引用计数就错乱了。会导致资源未释放或者程序崩溃的问题。所以只能指针中引用计数++、–是需要加锁的,也就是说引用计数的操作是线程安全的。
  2. 智能指针管理的对象存放在堆上,两个线程中同时去访问,会导致线程安全问题。
	void TestShared_Ptr2()
	{
		shared_ptr<int> sp(new int);
		cout << sp.UsePcount() << endl;

		//线程安全问题
		//引用计数的++/--不是原子操作,两个线程有可能会同时进行
		//比如:开始时,sp的_pcount是1,然后sp1的_pcount++时,sp2的_pcount同时也++
		//这时_pcount是2,然后sp1的_pcount析构,sp2的_pcount也析构,此时_pcount为0,资源被释放,sp被悬空出错
		//因此需要对其进行加锁解锁操作
		int n = 10000;
		thread t1([&]()
		{
			for (int i = 0; i < n; ++i)
			{
				shared_ptr<int> sp1(sp);
			}		
		});

		thread t2([&]()
		{
			for (int i = 0; i < n; ++i)
			{
				shared_ptr<int> sp2(sp);
			}
		});

		t1.join();
		t2.join();

		cout << sp.UsePcount() << endl;
	}

下面简化模拟实现了一份线程安全的SharedPtr来了解它的原理:

namespace Shared_Ptr_ThreadSafe
{
	template<class T>
	class shared_ptr
	{
	public:
		shared_ptr(T* ptr = nullptr)
			: _ptr(ptr)
			, _pcount(new int(1))
			, _pmtx(new mutex)
		{}

		shared_ptr(shared_ptr<T>& sp)
			: _ptr(sp._ptr)
			, _pcount(sp._pcount)
			, _pmtx(sp._pmtx)
		{
			AddRefCount();
		}

		shared_ptr<T>& operator=(shared_ptr<T>& sp)
		{
			if (this != &sp)
			{
				//减减引用计数,如果我是最后一个管理资源的对象,则释放资源
				Release();

				//我开始跟你一起管理资源
				_ptr = sp._ptr;
				_pcount = sp._pcount;
				_pmtx = sp._pmtx;

				AddRefCount();
			}
			return *this;
		}

		~shared_ptr()
		{
			Release();
		}

		void AddRefCount()
		{
			_pmtx->lock();
			++(*_pcount);
			_pmtx->unlock();
		}

		void Release()
		{
			bool flag = false;

			_pmtx->lock();
			if (--(*_pcount) == 0)
			{
				if (_ptr)
				{
					cout << "delete:" << _ptr << endl;
					delete _ptr;
					_ptr = nullptr;
				}

				delete _pcount;
				_pcount = nullptr;

				flag = true;
			}
			_pmtx->unlock();

			if (flag == true)
			{
				delete _pmtx;
				_pmtx = nullptr;
			}
		}

		int UsePcount()
		{
			return *_pcount;
		}

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

		T* operator->()
		{
			return _ptr;
		}
	private:
		T* _ptr;
		int* _pcount; //引用计数
		mutex* _pmtx;
	};
}

std::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;
	cout << node2.use_count() << endl;

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

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

循环引用分析:

  1. node1和 node2两个智能指针对象指向两个节点,引用计数变成1,我们不需要手动 delete。
  2. node1的 _next指向node2,node2的 _prev指向 node1,引用计数变成2。
  3. node1和 node2析构,引用计数减到1,但是 _next还指向下一个节点。但是 _prev还指向上一个节点。
  4. 也就是说 _next析构了,node2就释放了。
  5. 也就是说 _prev析构了,node1就释放了。
  6. 但是 _next属于 node1的成员,node1释放了,_next才会析构,而 node1由 _prev管理,_prev属于 node2成员,所以这就叫循环引用,谁也不会释放。

在这里插入图片描述
解决方案:在引用计数的场景下,把节点中的 _prev和 _next改成 weak_ptr就可以了
原理就是,node1->_next = node2;和 node2->_prev = node1;时,weak_ptr的 _next和 _prev不会增加node1和node2的引用计数。

//严格来说weak_ptr不是智能指针,因为他没有RAII资源管理机制
//专门解决shared_ptr的循环引用问题
template<class T>
class weak_ptr
{
public:
	//显示生成默认的构造函数
	weak_ptr() = default;

	weak_ptr(const shared_ptr<T>& sp)
		: _ptr(sp.GetPtr())
	{}

	weak_ptr<T>& operator=(const shared_ptr<T>& sp)
	{
		_ptr = sp.GetPtr();
		return *this;
	}

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

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

//shared_ptr的循环引用问题
struct ListNode
{
	weak_ptr<ListNode> _next;
	weak_ptr<ListNode> _prev;
	int _val;
	~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;
}

如果不是new出来的对象如何通过智能指针管理呢?其实shared_ptr设计了一个删除器来解决这个问题

// 定制删除器(了解)
#include<memory>
class A
{
public:
	~A()
	{
		cout << "~A()" << endl;
	}
private:
	int _a1;
	int _a2;
};

template<class T>
struct DeleteArry
{
	void operator()(T* pa)
	{
		delete[] pa;
	}
};

struct Free
{
	void operator()(void* p)
	{
		cout << "free(p)" << endl;

		free(p);
	}
};

int main()
{
	std::shared_ptr<A> sp1(new A);
	std::shared_ptr<A> sp2(new A[2], DeleteArry<A>());
	std::shared_ptr<A> sp3((A*)malloc(sizeof(A)), Free());

	return 0;
}

C++11和boost中智能指针的关系

  1. C++ 98 中产生了第一个智能指针 auto_ptr.
  2. C++ boost给出了更实用的 scoped_ptr和 shared_ptr和 weak_ptr.
  3. C++ 11,引入了unique_ptr和 shared_ptr和 weak_ptr。需要注意的是 unique_ptr对应 boost的 scoped_ptr。并且这些智能指针的实现原理是参考 boost中的实现的

RAII扩展

RAII思想除了可以用来设计智能指针,还可以用来设计守卫锁,防止异常安全导致的死锁问题。

// 智能指针是RAII思想的一种应用的体现
// 本质RAII就是借助构造函数和析构函数来搞事情,因为构造函数和析构函数的特点都是自动调用
#include<mutex>

// 使用RAII思想设计的锁管理守卫
template<class Lock>
class LockGuard
{
public:
	LockGuard(Lock& lock)
		:_lk(lock)
	{
		_lk.lock();
	}

	~LockGuard()
	{
		cout << "解锁" << endl;
		_lk.unlock();
	}

	LockGuard(LockGuard<Lock>&) = delete;
	LockGuard<Lock>& operator=(LockGuard<Lock>&) = delete;
private:
	Lock& _lk;  // 注意这里是引用
};

int div()
{
	int a, b;
	cin >> a >> b;
	if (b == 0)
	{
		throw invalid_argument("除0错误");
	}	
	return a / b;
}

void Func()
{
	mutex mtx;
	LockGuard<mutex> lg(mtx);

	cout << div() << endl;   // 假设div函数有可能抛异常
}

int main()
{
	try
	{
		Func();
	}
	catch (exception& e)
	{
		cout << e.what() << endl;
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值