智能指针(1)

        运用C++标准中的智能指针时(std::shared_ptr),可能会出现智能指针释放失效的问题,如以下代码。

class Parent;
typedef std::shared_ptr<Parent> Parent_ptr;

class Child
{
public:
    Parent_ptr father;
    Child()
    {
        std::cout << "hello child\n";
    }
    ~Child()
    {
        std::cout << "bye child\n";
    }
};

typedef std::shared_ptr<Child> Child_ptr;

class Parent
{
public:
    Child_ptr son;
    Parent()
    {
        std::cout << "hello parent\n";
    }
    ~Parent()
    {
        std::cout << "bye parent\n";
    }
};

void testParentAndChild()
{
    Parent_ptr p(new Parent());
    Child_ptr c(new Child());
    p->son = c;
    c->father = p;
}

         当调用testParentAndChild完成后,可以看出正常调用了Parent与Child的构造函数,但却没有调用析构函数,原因在于在执行完

Parent_ptr p(new Parent());
Child_ptr c(new Child());

代码后,p与c中的use_count均为1,但执行赋值运算后,相当于拷贝了一次p与c,其中的use_count都变为了2,。所以在函数结束时use_count减一不为0,造成内存泄漏。

         通过使用弱指针(std::weak_ptr)来打破循环,weak_ptr指向的资源只有在有其他智能指针指向时才是有效的,否则是无效的。

        通过lock()可以返回判断资源是否被其他智能指针管理。通过调用reset()可以手动不管理资源,lock()函数返回无效指针。

        使用weak_ptr后打破循环可以正常使用。

class Parent;
typedef std::shared_ptr<Parent> Parent_ptr;
typedef std::weak_ptr<Parent> WeakParent_ptr;
class Child
{
public:
    WeakParent_ptr father;
    Child()
    {
        std::cout << "hello child\n";
    }
    ~Child()
    {
        std::cout << "bye child\n";
    }
};
typedef std::shared_ptr<Child> Child_ptr;
typedef std::weak_ptr<Child> WeakChild_ptr;
class Parent
{
public:
    Child_ptr son;
    Parent()
    {
        std::cout << "hello parent\n";
    }
    ~Parent()
    {
        std::cout << "bye parent\n";
    }
};
void testParentAndChild()
{
    Parent_ptr p(new Parent());
    Child_ptr c(new Child());
    p->son = c;
    c->father = p;
}

         在一个类中运用weak_ptr便可以打破,不过是在第一个类或者在第二个类或者在两个类中使用哪种更好,后续有机会进行补充。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值