C++智能指针使用和详解

智能指针

auto_ptr

C++98版本的库中就提供了auto_ptr的智能指针。下面演示的auto_ptr的使用及问题。

// C++库中的智能指针都定义在memory这个头文件中
#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);
 // auto_ptr的问题:当对象拷贝或者赋值后,前面的对象就悬空了
 // C++98中设计的auto_ptr问题是非常明显的,所以实际中很多公司明确规定了不能使用auto_ptr
 ap->_year = 2018;    //运行到这里程序会奔溃
 return 0; }

上面的程序运行到ap->_year = 2018; 会崩溃,为什么?
想想如果有多个对象管理同一份资源,应该根据什么条件来释放资源了?
这里之所以会崩溃,就是因为auto_ptr在拷贝或赋值时会将之前的指针悬空,所以这里实际上操作的是一个空指针,当然会崩溃了。

auto_ptr的简单实现,从下面的模拟实现中可以很明显的看到该智能指针的缺陷

// 模拟实现一份简答的AutoPtr,了解原理
template<class T>
class AutoPtr
{
public:
 AutoPtr(T* ptr = NULL)
 : _ptr(ptr)
 {}
 
 ~AutoPtr()
 {
 if(_ptr)
 delete _ptr;
 }
 
 // 一旦发生拷贝,就将ap中资源转移到当前对象中,然后令ap与其所管理资源断开联系,
 // 这样就解决了一块空间被多个对象使用而造成程序奔溃问题
 AutoPtr(AutoPtr<T>& ap)
 : _ptr(ap._ptr)
 {
 ap._ptr = NULL;
 }
 
 AutoPtr<T>& operator=(AutoPtr<T>& ap)
 {
 // 检测是否为自己给自己赋值
 if(this != &ap)
 {
 // 释放当前对象中资源
 if(_ptr)
 delete _ptr;
 
 // 转移ap中资源到当前对象中
 _ptr = ap._ptr;
 ap._ptr = NULL;
 }
 
 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

那么如何解决上述指针悬空的问题了?
C++11提供了unique_ptr来解决上述指针悬空的问题,该智能指针解决该问题的方法简单粗暴,即直接不让上述指针悬空的问题出现。如下演示

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

	// unique_ptr的设计思路非常的粗暴-防拷贝,也就是不让拷贝和赋值。
	unique_ptr<Date> copy(up);   //这里编译不会通过,无法调用拷贝构造
	return 0;
}

简单模拟

// 模拟实现一份简答的UniquePtr
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++98防拷贝的方式:只声明不实现+声明成私有
 UniquePtr(UniquePtr<T> const &);
 UniquePtr & operator=(UniquePtr<T> const &);
 
 // C++11防拷贝的方式:delete
 UniquePtr(UniquePtr<T> const &) = delete;
 UniquePtr & operator=(UniquePtr<T> const &) = delete;
 
private:
 T * _ptr;
};

shared_ptr

很明显unique_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实现原理:

  1. shared_ptr在其内部,给每个资源都维护了着一份计数,用来记录该份资源被几个对象共享。
  2. 在对象被销毁时(也就是析构函数调用),就说明自己不使用该资源了,对象的引用计数减一。
  3. 如果引用计数是0,就说明自己是最后一个使用该资源的对象,必须释放该资源;
  4. 如果不是0,就说明除了自己还有其他对象在使用该份资源,不能释放该资源,否则其他对象就成野指针了。
// 模拟实现一份简答的SharedPtr,了解原理
#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));  //引用计数为_pRefCount ==1
 SharedPtr<int> sp2(sp1);    //_pRefCount++
 *sp2 = 20;
 cout << sp1.UseCount() << endl;    //UseCount()获得引用计数  2
 cout << sp2.UseCount() << endl;   //2
 SharedPtr<int> sp3(new int(10));  //   另一份资源
 sp2 = sp3;            //sp2管理新资源,原资源计数-1
 cout << sp1.UseCount() << endl;   //1
 cout << sp2.UseCount() << endl;    //2
 cout << sp3.UseCount() << endl;     //2
 sp1 = sp3;          //sp1也管理了后开辟的资源,此时sp1计数变为0,释放资源
 cout << sp1.UseCount() << endl;  //3
 cout << sp2.UseCount() << endl;   //3
 cout << sp3.UseCount() << endl;  //3
 return 0; }
 //生命周期结束,所有资源被释放
 //上述实现并不是完美,只是为了理解而实现的简单版本

weak_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;
 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的引用计数才会变成0,才会释放。
  5. 也就是说_prev指向的结点析构了,node1的引用计数才会变成0,才会释放。
  6. 但是_next属于node1的成员,node1释放了,_next才会析构,而node1又由node2的_prev管理,所以这就造成了谁的引用计数都不能变为0,谁也不会释放,这就叫循环引用。

没错这时就轮到weak_ptr登场了。
解决方法:

// 解决方案:在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了
// 原理就是,node1->_next = node2;和node2->_prev = node1;时weak_ptr的_next和_prev不会增加
node1和node2的引用计数。
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; }

注意:weak_ptr是专门为shared_ptr而生的,它不具备普通指针的行为operator*和operator->,所以请不要单独使用weak_ptr。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值