异常:bad_weak_ptr 而 shared_from_this [英] exception: bad_weak_ptr while shared_from_this

查看:63
本文介绍了异常:bad_weak_ptr 而 shared_from_this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有基类:

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

推荐答案

为了enable_shared_from_this 工作,你需要在调用shared_from_this()<之前将指向this的指针存储在std::shared_ptr中/代码>.

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().

注意,在对象 t 上调用 shared_from_this 之前,必须有一个拥有 t 的 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 管理:

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

这篇关于异常:bad_weak_ptr 而 shared_from_this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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