升压shared_from_this和析构函数 [英] Boost shared_from_this and destructor

查看:667
本文介绍了升压shared_from_this和析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,它不允许从类中调用shared_from_this在析构函数:

I found that it is not allowed to call shared_from_this in the destructor from a class:

https://svn.boost.org/trac/boost/ticket/147

这行为是设计使然。由于析构函数会销毁对象,它是不是安全地创建一个shared_ptr到它,因为它会变成一次晃来晃去的析构函数结束。

This behavior is by design. Since the destructor will destroy the object, it is not safe to create a shared_ptr to it as it will become dangling once the destructor ends.

我理解的说法,但如果我需要一个shared_from_this指针清理引用(而不是共享所有权)。

I understand the argument, but what if I need a "shared_from_this" pointer for cleaning up references ( not for sharing owner ship).

下面就是我不使用shared_ptr的一个例子:

Here is an example where I'm not using shared_ptr:

class A{
public:
    A( Manager * m ) : m_(m) {
        m_->add(this);
    }

    ~A() {
        m_->remove(this);
    }

private:
    Manager * m_;
};

在这里,我试图把它翻译成共享指针。但我不能找到一个好办法来完成析构函数:

Here I have tried to translate it into shared pointers. But I can not find a good way to finish the destructor:

class A : public boost::enable_shared_from_this< A > {
public:
    typedef boost::shared_ptr< A > Ptr;

    static Ptr create( Manager * m ) {
        Ptr p( new A(m));
        p->init();
        return p;
    }

    ~A() {
        // NON-WORKING
        // m_->remove( shared_from_this() );
    }

private:
    A( Manager * m ) : m_(m) { }

    void init() {
        m_->add(shared_from_this());
    }

    Manager * m_;
};

我如何能实现的例子中的析构函数上面?

How can I implement the destructor in the example above?

推荐答案

如果你的经理有一个的shared_ptr 来你的对象,然后将其拥有它。
因此,你的对象不得破坏,是经理还是要对它的引用。

If your Manager has a shared_ptr to your object, then it owns it. Thus your object shall not be destructed, as the Manager still have a reference to it.

您可以传递一个弱指针的经理,但它的管理工作,检查指针仍然有效,如果不将其删除。

You may pass a weak pointer to the Manager, but then it's the work of the manager to check that the pointer is still valid, and delete it if not.

您的问题很有趣,但你的情况是由误解造成的。只要对象拥有到对象的参考,它是不会被破坏的shared_ptr的目的。要调用析构函数,你应该叫手动删除该指针,与shared_ptr的工作时,这是一个不好的行为。

Your question is interesting, but your case is caused by a misconception. As long as an object own a reference to your object, it's the aim of shared_ptr that it will not be destructed. For the destructor to be called, you should have manually called delete on the pointer, which is a bad behavior when working with shared_ptr.

简单的定义谁真正拥有的对象,并给他们的shared_ptr。如果$ C $一个C部分偶尔需要你的对象 - 如果存在的话 - 然后给它一个的weak_ptr

Simple define who really own the object, and give them the shared_ptr. If a part of code occasionally need your object - if it exists - then give it a weak_ptr.

这篇关于升压shared_from_this和析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆