正确的做法
weak_ptr主要是配合share_ptr来实现应用计数,同时不会发生循环引用。
参考:http://www.cnblogs.com/TianFang/archive/2008/09/20/1294590.html
#include "boost/smart_ptr.hpp"
#include "boost/weak_ptr.hpp"
#include<iostream>
using namespace std;
using namespace boost;
class node;
typedef boost::weak_ptr<node> ptr_type;
class node
{
public:
node();
~node();
int value_;
ptr_type next;
};
node::node()
{
cout<<"node()"<<endl;
}
node::~node()
{
cout<<"~node()"<<endl;
}
int main(int,char**)
{
auto p1 = boost::make_shared<node>();
auto p2 = boost::make_shared<node>();
p1->next = p2;//weak_ptr(const share_ptr&) //不增加引用计数
p2->next = p1;//weak_ptr(const share_ptr&) //不增加引用计数
return 0;
};
程序输出:
node()node()
~node()
~node()
请按任意键继续. . .
导致循环引用的情形
#include "boost/smart_ptr.hpp"
#include "boost/weak_ptr.hpp"
#include<iostream>
using namespace std;
using namespace boost;
class node;
//typedef boost::weak_ptr<node> ptr_type;
typedef boost::shared_ptr<node> ptr_type;//这样会发生循环引用
class node
{
public:
node();
~node();
int value_;
ptr_type next;//是否会循环引用取决于ptr_type的类型
};
node::node()
{
cout<<"node()"<<endl;
}
node::~node()
{
cout<<"~node()"<<endl;
}
int main(int,char**)
{
auto p1 = boost::make_shared<node>();
auto p2 = boost::make_shared<node>();
p1->next = p2;//weak_ptr(const share_ptr&) //不增加引用计数
p2->next = p1;//weak_ptr(const share_ptr&) //不增加引用计数
return 0;
};
程序输出(只有创建对象,没有释放对象):
node()
node()
请按任意键继续. . .