Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exception: bad_weak_ptr while shared_from_this

Tags:

c++

shared-ptr

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()));
    }
}
like image 405
Ir S Avatar asked Nov 26 '15 08:11

Ir S


1 Answers

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>(); }
}
like image 178
el.pescado - нет войне Avatar answered Oct 19 '22 00:10

el.pescado - нет войне