weak_ptr简介

2009年11月16日 | 分类: C/C++ | 标签: ,

上次帖的《shared_ptr简介》已经是1年前的事了,时间过得好快。
平时很少使用weak_ptr,简单复习下。

shared_ptr引用一个对象时,引用计数会加1,也就是说只要shared_ptr还存在,那么shared_ptr引用的对象也一定还存在。
weak_ptr则不同,weak_ptr引用一个对象时,不会改变引用计数,也就是说weak_ptr存在时,weak_ptr引用的对象不一定还存在。

关于weak_ptr的用途,举得最多例子就是用来解决循环引用的问题,看下面的例子:

 
#include <iostream>
#include <memory>
 
class A;
class B;
 
class A
{
public:
    std::tr1::shared_ptr<B> b;
 
    ~A()
    {
        std::cout << "A destructor" << std::endl;
    }
};
 
class B
{
public:
    std::tr1::shared_ptr<A> a;
 
    ~B()
    {
        std::cout << "B destructor" << std::endl;
    }
};
 
void test()
{
    std::tr1::shared_ptr<A> a(new A());
    std::tr1::shared_ptr<B> b(new B());
 
    a->b = b;
    b->a = a;
}
 
int main()
{
    test();
}

运行这个例子,会发现a和b都没有被销毁,因为a和b互相引用对方,导致它们的引用计数永远为1,最终导致内存泄漏。
解决这种循环引用的一个方法就是在a、b的任何一方使用weak_ptr即可:

 
#include <iostream>
#include <memory>
 
class A;
class B;
 
class A
{
public:
    std::tr1::shared_ptr<B> b;
 
    ~A()
    {
        std::cout << "A destructor" << std::endl;
    }
};
 
class B
{
public:
    std::tr1::weak_ptr<A> a;
 
    ~B()
    {
        std::cout << "B destructor" << std::endl;
    }
};
 
void test()
{
    std::tr1::shared_ptr<A> a(new A());
    std::tr1::shared_ptr<B> b(new B());
 
    a->b = b;
    b->a = a;
}
 
int main()
{
    test();
}

(以上代码VS 2008 SP1编译测试通过)

目前还没有任何评论.