c11通过share_from_this构造另一类对象抛异常
异常显示:
inline void
__throw_bad_weak_ptr()
{ _GLIBCXX_THROW_OR_ABORT(bad_weak_ptr()); }
//代码如下:
#include <memory>
//class HashNode;
class node;
class mission;
typedef std::shared_ptr<node> node_ptr;
typedef std::shared_ptr<mission> mission_ptr;
//typedef std::shared_ptr<HashNode> hashnode_ptr;
//typedef std::weak_ptr<HashNode> hashnode_weak_ptr;
class mission
{
public:
mission( const node_ptr & pParent)
: m_pParent(pParent){ }
~mission()
{
if (m_pParent)
{ }
}
protected:
node_ptr m_pParent;
};
class node : public std::enable_shared_from_this<node>
{
public:
node() {
}
void make()
{
mission_ptr pMission = std::make_shared<mission>( this->shared_from_this());
}
~node() {
}
};
int main(void)
{
node a;
a.make();
return 0;
}
异常原因:
The bug is that you're using shared_from_this() on an object which has no shared_ptr pointing to it.
This violates a precondition of shared_from_this(), namely that at least one shared_ptr must already have been created (and still exist) pointing to this.
调用shared_from_this的类必须至少有一个share_ptr指向它。
正确的如下,应该改成:
int main(void)
{
std::shared_ptr<node> a(new node());
a->make();
return 0;
}
而在构造函数里面调用share_from_this也会报错,因为对象还没构造完成
class node : public std::enable_shared_from_this<node>
{
public:
node() {
mission_ptr pMission = std::make_shared<mission>( this->shared_from_this()); //报错,应该在构造函数外的地方调用share_from_this
}
~node()
{
}
};
int main(void)
{
std::shared_ptr<node> a(new node());
return 0;
}
转载于:https://blog.51cto.com/mingtangduyao/1741444