关于这个问题的前提我们都知道,
shared_ptr和weak_ptr都是带有引用计数的智能指针,它俩的主要区别就是:
shared_ptr可以改变引用计数的值,但是weak_ptr只是资源的观察者不会对资源的引用计数进行加1的操作
但是我们为什么要引入weak_ptr这个智能指针呢?
现在我们看如下的例子中:
#include<iostream>
using namespace std;
class B;
class A
{
public:
A(){cout<<"A()"<<endl;}
~A(){cout<<"~A()"<<endl;}
shared_ptr<B> _ptr;
};
class B
{
public:
B(){cout<<"B()"<<endl;}
~B(){cout<<"~B()"<<endl;}
shared_ptr<A> _ptr;
};
int main()
{
shared_ptr<A> _pa(new A());
shared_ptr<B> _pb(new B());
cout<< _pa.use_count()<<endl;
cout<< _pb.use_count()<<endl;
return 0;
}
其运行结果为
可以看到我们再main函数栈区上定义的俩个智能指针所引用的资源都被正常的释放掉了。
我们对代码进行简单的修改,再看结果:
int main()
{
shared_ptr<A> _pa(new A());
shared_ptr<B> _pb(new B());
_pa->_ptr = _pb;
_pb->_ptr = _pa;
cout << _pa.use_count() << endl;
cout << _pb.use_count() << endl;
return 0;
}
这便是所谓的智能指针的引用交叉问题,造成了资源泄漏。
我们解决这种问题的办法一般就是使用weak_ptr来引用资源。
代码如下:
#include<iostream>
using namespace std;
class B;
class A
{
public:
A() { cout << "A()" << endl; }
~A() { cout << "~A()" << endl; }
void fun()
{
cout << "A 类成员变量中非常好用的一个方法" << endl;
}
//shared_ptr<B> _ptr;
weak_ptr<B> _ptr;
};
class B
{
public:
B() { cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
//shared_ptr<A> _ptr;
void fun()
{
shared_ptr<A> _ps = _ptr.lock();
if (_ps != nullptr)
{
_ps->fun();
}
}
weak_ptr<A> _ptr;
};
int main()
{
shared_ptr<A> _pa(new A());
shared_ptr<B> _pb(new B());
_pa->_ptr = _pb;
_pb->_ptr = _pa;
cout << _pa.use_count() << endl;
cout << _pb.use_count() << endl;
_pb->fun();
return 0;
}
同时我们使用的弱智能指针weak_ptr的时候,当我们需要使用操作资源的时候,必须使用lock方法对弱智能指针进行提升操作。如例中操作。