gpt4 book ai didi

c++ - 异常 : bad_weak_ptr while shared_from_this

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:42 30 4
gpt4 key购买 nike

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

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

这里我想在构造函数中设置“问题”对象:

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

还有派生类,我想在派生类中将智能指针发送到基础抽象类,但出现异常:

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 构造函数设为私有(private)并公开工厂方法以确保创建的每个 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>(); }
}

关于c++ - 异常 : bad_weak_ptr while shared_from_this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33933550/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com