我这样做时出现异常:std :: bad_weak_ptr-> shared_from_this()
template<typename TChar>
class painter_record_t
{
.......
private:
std::shared_ptr<i_painter_t> _owner;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我想在构造函数中设置“问题”对象:
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)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
我有基类:
class i_painter_t
{
public:
virtual std::unique_ptr<painter_record_t<char>> get_entry() = 0;
}
Run Code Online (Sandbox Code Playgroud)
和派生类,在其中我想将智能指针发送到基本抽象类,但会出现异常:
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())));
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试这样做,但是有同样的问题:
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()));
}
}
Run Code Online (Sandbox Code Playgroud)
为了enable_shared_from_this工作,您需要this在std::shared_ptr之前存储指向的指针shared_from_this()。
请注意,在对对象t调用shared_from_this之前,必须有一个拥有t的std :: shared_ptr。
您可能希望将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>(); }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3384 次 |
| 最近记录: |