从分离一个shared_ptr的指针? [英] Detach a pointer from a shared_ptr?

查看:268
本文介绍了从分离一个shared_ptr的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  如何释放从boost ::指针shared_ptr的?


我的界面的函数返回一个指向对象。用户应该采取对象的所有权。我不想返回Boost.shared_ptr,因为我不希望强制客户端使用升压。但是在内部,我想指针存储在一个shared_ptr至prevent内存泄漏等异常的情况下,似乎有没有办法从一个共享指针分离的指针。这里任何想法?


解决方案

什么你要找的是一个发布功能; 的shared_ptr 不具有释放功能。 %的提升手动


  

Q值。为什么shared_ptr不提供一个release()函数?


  
  

一个。的shared_ptr不能放弃所有权除非它是唯一的(),因为其它拷贝仍然销毁对象。


  
  

考虑:


 的shared_ptr< INT>一个(新int);在
shared_ptr的< INT> B(A); // a.use_count()== b.use_count()== 2为int * p = a.release();//现在谁拥有P + b仍然会调用析构函数删除就可以了。


  

此外,通过释放()返回的指针将难以可靠地释放,作为源的shared_ptr可能已被用定制删除创建


两个选项,你可能会考虑:


  • 您可以使用的std :: TR1的:: shared_ptr的,这就需要你的用户使用C ++库实现支持TR1的的使用促进;至少这会给他们两者的选项。

  • 您可以实现自己的的boost :: shared_ptr的式的共享指针,并使用你的外部接口。

您也可以看一下在讨论关于<一个这个问题, href=\"http://stackoverflow.com/questions/335330/using-boostsharedptr-in-a-librarys-public-interface\">using提高:: shared_ptr的一个库的公共接口。

Possible Duplicate:
How to release pointer from boost::shared_ptr?

A function of my interface returns a pointer to an object. The user is supposed to take ownership of that object. I do not want to return a Boost.shared_ptr, because I do not want to force clients to use boost. Internally however, I would like to store the pointer in a shared_ptr to prevent memory leaks in case of exceptions etc. There seems to be no way to detach a pointer from a shared pointer. Any ideas here?

解决方案

What you're looking for is a release function; shared_ptr doesn't have a release function. Per the Boost manual:

Q. Why doesn't shared_ptr provide a release() function?

A. shared_ptr cannot give away ownership unless it's unique() because the other copy will still destroy the object.

Consider:

shared_ptr<int> a(new int);
shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2

int * p = a.release();

// Who owns p now? b will still call delete on it in its destructor.

Furthermore, the pointer returned by release() would be difficult to deallocate reliably, as the source shared_ptr could have been created with a custom deleter.

Two options you might consider:

  • You could use std::tr1::shared_ptr, which would require your users to use a C++ library implementation supporting TR1 or to use Boost; at least this would give them the option between the two.
  • You could implement your own boost::shared_ptr-like shared pointer and use that on your external interfaces.

You might also look at the discussion at this question about using boost::shared_ptr in a library's public interface.

这篇关于从分离一个shared_ptr的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆