Detach a pointer from a shared_ptr?(从 shared_ptr 中分离一个指针?)
问题描述
<块引用>可能的重复:
如何从 boost::shared_ptr 释放指针?
我的接口的一个函数返回一个指向对象的指针.用户应该拥有该对象的所有权.我不想返回 Boost.shared_ptr,因为我不想强迫客户端使用 boost.然而,在内部,我想将指针存储在 shared_ptr 中以防止出现异常等情况下的内存泄漏.似乎无法将指针与共享指针分离.这里有什么想法吗?
你要找的是一个 release 函数;shared_ptr 没有发布功能.根据 Boost 手册:
问.为什么 shared_ptr 不提供 release() 函数?
A.shared_ptr 不能放弃所有权,除非它是 unique() 因为另一个副本仍然会破坏对象.
考虑:
shared_ptr一个(新的整数);shared_ptr乙(一);//a.use_count() == b.use_count() == 2int * p = a.release();//现在谁拥有 p?b 仍然会在其析构函数中调用 delete . <块引用>
此外,release() 返回的指针将难以可靠地释放,因为源 shared_ptr 可能是使用自定义删除器创建的.
您可能会考虑的两个选项:
- 您可以使用
std::tr1::shared_ptr,这将要求您的用户使用支持 TR1 或 的 C++ 库实现以使用 Boost;至少这会让他们在两者之间做出选择. - 您可以实现自己的
boost::shared_ptr类似的共享指针,并在您的外部接口上使用它.
您还可以查看有关使用 boost:: 的讨论:库公共接口中的 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 中分离一个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 shared_ptr 中分离一个指针?
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
