首页 > 其他 > 详细

c11通过share_from_this构造另一类对象抛异常

时间:2016-02-10 06:40:28      阅读:1195      评论:0      收藏:0      [点我收藏+]
异常显示:
  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;
}

 

c11通过share_from_this构造另一类对象抛异常

原文:http://mingtangduyao.blog.51cto.com/4876371/1741444

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!