boost::shared_ptr的使用方法(二)

2014-11-24 09:55:00 · 作者: · 浏览: 1
ldren; typedef boost::shared_ptr parent_ptr; typedef boost::shared_ptr children_ptr; class parent { public: children_ptr children; }; class children {public: parent_ptr parent; }; void test() { boost::shared_ptr father( new parent); boost::shared_ptr son(new children); father->children = son;  //user_count() == 2 son->parent = father;  //user_count() == 2 }

在这个例子中,出现了循环引用计数,赋值后use_count()变为2,出函数后变为1,资源无法被释放。boost的解决方法是采用weak_ptr来保存。

class parent {public:
   boost::weak_ptr
          
            children;
};

class children {public:
     boost::weak_ptr
           
             parent; };
           
          

因为boost不会影响weak_ptr不会影响引用计数,不会造成循环引用计数。

(4) 不要把this指针给shared_ptr

将this指针赋给shared_ptr会出现this指针被释放两次的危险,如下面的代码,会在t释放时析构一次,shared_ptr释放时析构一次。

class test {
  public:
    boost::shared_ptr
          
            pget() {
      return boost::shared_ptr
           
            (this); } }; test t; boost::shared_ptr
            
              pt = t.pget();
            
           
          

boost库提供的解决方法是:使用enable_shared_from_this来实现。

class test : public boost::enable_shared_from_this
          
            {
  public:
    boost::shared_ptr
           
             pget() { return shared_from_this(); } }; test t; boost::shared_ptr
            
              pt = t.pget();
            
           
          

4. std::tr1::shared_ptr和boost::shared_ptr

  在新版本的C++标准中引用shared_ptr智能指针,名空间是std::tr1::shared_ptr。它和boost::shared_ptr的用法相同,在gcc4.3.x及以上的版本加选项-std=gnu++0x即可使用。

<script type="text/java script">
<script type="text/java script">BAIDU_CLB_fillSlot("771048");
点击复制链接 与好友分享! 回本站首页
<script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
分享到: 更多
<script type="text/java script" id="bdshare_js" data="type=tools&uid=12732"> <script type="text/java script" id="bdshell_js"> <script type="text/java script"> var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}}; document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000)
您对本文章有什么意见或着疑问吗?请到 论坛讨论您的关注和建议是我们前行的参考和动力
上一篇: C++ 在继承中虚函数、纯虚函数、普通函数,三者的区别
下一篇: MFC 如何修改BMP图片的大小
相关文章
如何用C++编程获得某台机器的IP地址?
<script type="text/java script">BAIDU_CLB_fillSlot("182716");
<script type="text/java script">BAIDU_CLB_fillSlot("517916");
图文推荐
<iframe src="http://www.2cto.com/uapi.php tid=282187&catid=339&title=Ym9vc3Q6OnNoYXJlZF9wdHK1xMq508O3vbeo&forward=http://www.2cto.com/kf/201402/282187.html" width="100%" height="100%" id="comment_iframe" name="comment_iframe" frameborder="0" scrolling="no">
<script type="text/java script">BAIDU_CLB_fillSlot("771057");
排行
热门