exception: bad_weak_ptr while shared_from_this

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 14:16:22

问题


I get exception: std::bad_weak_ptr when I do this->shared_from_this()

template<typename TChar>
class painter_record_t
{
.......
private:
    std::shared_ptr<i_painter_t> _owner;
}

Here I want to set the "problem" object in constructor:

template<typename TChar>
class stream_record_t : public painter_record_t<TChar>
{
public:
    stream_record_t(std::shared_ptr<i_painter_t> owner) : painter_record_t(owner)
    {
    //...
    }
}

I have the base class:

class i_painter_t
{
public:
    virtual std::unique_ptr<painter_record_t<char>> get_entry() = 0;
}

And derived class, in which I want to send the smart pointer to the base abstract class, but get an exception:

class painter_t : public i_painter_t, public std::enable_shared_from_this<painter_t>
{
public:         

    std::unique_ptr<painter_record_t<char>> get_entry()
    {               
        return std::unique_ptr<painter_record_t<char>>(new stream_record_t<char>(static_cast< std::shared_ptr<i_painter_t> >(this->shared_from_this())));
    }
}

I also try this, but have the same problem:

class painter_t : public i_painter_t, public std::enable_shared_from_this<painter_t>
{
public:         

    std::unique_ptr<painter_record_t<char>> get_entry()
    {               
        return std::unique_ptr<painter_record_t<char>>(new stream_record_t<char>(this->shared_from_this()));
    }
}

回答1:


In order for enable_shared_from_this to work, you need to store pointer to this in std::shared_ptr prior to calling shared_from_this().

Note that prior to calling shared_from_this on an object t, there must be a std::shared_ptr that owns t.

You may want to make painter_t constructor private and expose a factory method to ensure that every painter_tcreated is managed by shared_ptr:

class painter_t : public i_painter_t, public std::enable_shared_from_this<painter_t>
{
public:
    static std::shared_ptr<painter_t> create() { return std::make_shared<painter_t>(); }
}


来源:https://stackoverflow.com/questions/33933550/exception-bad-weak-ptr-while-shared-from-this

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!