一,引用计数带来的循环引用问题
下面是一个简单的例子:
#include <iostream>
#include <memory>
using namespace std;
class parent;
class children;
class parent{
public:
~parent(){
cout<<"destroying parent"<<endl;
}
public:
shared_ptr<children> m_children;
};
class children{
public:
~children(){
cout<<"destroying children"<<endl;
}
public:
shared_ptr<parent> m_parent;
};
int main() {
shared_ptr<parent> p1(new parent);
shared_ptr<children> p2(new children);
p1->m_children = p2;
p2->m_parent = p1;
cout<<p1.use_count()<<endl;
cout<<p2.use_count()<<endl;
return 0;
}
输出结果
2
2
Process returned 0 (0x0) execution time : 0.010 s
Press any key to continue.
程序分析
parent 类中有指向children 类的shared_ptr智能指针,children 类中有指向parent类的shared_ptr 智能指针,他们相互指向会构成shared_ptr 的循环引用。
二,使用weak_ptr来解决循环引用
weak_ptr是为了配合shared_ptr而引入的一种智能指针,它更像是shared_ptr的一个助手而不是智能指针,因为它不具有普通指针的行为,没有重载operator*和->。它的最大作用在于协助shared_ptr工作,像旁观者那样观测资源的使用情况,弱引用能检测到所管理的对象是否已经被释放,从而避免访问非法内存。同时,weak_ptr 必须从一个share_ptr或者另一个weak_ptr转换而来,不能使用new 对象进行构造。由于弱引用不更改引用计数,类似普通指针,只要把循环引用的一方使用弱引用,即可解除循环引用。下面是对上面的例子的改进:把父类中的引用改为weak_ptr。
#include <iostream>
#include <memory>
using namespace std;
class parent;
class children;
class parent{
public:
~parent(){
cout<<"destroying parent"<<endl;
}
public:
weak_ptr<children> m_children;
};
class children{
public:
~children(){
cout<<"destroying children"<<endl;
}
public:
shared_ptr<parent> m_parent;
};
int main() {
shared_ptr<parent> p1(new parent);
shared_ptr<children> p2(new children);
p1->m_children = p2;
p2->m_parent = p1;
cout<<p1.use_count()<<endl;
cout<<p2.use_count()<<endl;
return 0;
}
输出结果
2
1
destroying children
destroying parent
Process returned 0 (0x0) execution time : 0.033 s
Press any key to continue.
三,总结
虽然通过弱引用指针可以有效的解除循环引用,但这种方式必须在程序员能预见会出现循环引用的情况下才能使用,也可以是说这个仅仅是一种编译期的解决方案,如果程序在运行过程中出现了循环引用,还是会造成内存泄漏的。因此,不要认为只要使用了智能指针便能杜绝内存泄漏。毕竟,对于C++来说,由于没有垃圾回收机制,内存泄漏对每一个程序员来说都是一个非常头痛的问题。