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()));
}
}
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_t
created 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>(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With