在这个例子中,出现了循环引用计数,赋值后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)
- 相关文章
- <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");
- 排行
- 热门
- 430 | C++ STL学习之三:容器deque深入学习
- 389 | c++模板详解
- 330 | C/C++之define用法小结
- 323 | WinExec()和system()的区别
- 322 | pthread 简要使用指南(一) pthrea
- 305 | cocos2d-x CCRotateTo 对初始角,旋
- 239 | 讨论nullptr和NULL
- 235 | Sock.IO上传AppStore出现non-public




