例外:bad_weak_ptr 而 shared_from_this

exception: bad_weak_ptr while shared_from_this

我遇到异常:std::bad_weak_ptr 当我这样做时->shared_from_this()

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

这里我想在构造函数中设置"problem"对象:

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)
    {
    //...
    }
}

我有基础class:

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

和派生class,其中我想将智能指针发送到基础抽象class,但得到一个异常:

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())));
    }
}

我也试过这个,但是有同样的问题:

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()));
    }
}

为了 enable_shared_from_this 工作,您需要在调用 shared_from_this().

之前将指向 this 的指针存储在 std::shared_ptr

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

您可能希望将 painter_t 构造函数设为私有并公开一个工厂方法,以确保创建的每个 painter_t 都由 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>(); }
}