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 中分离一个指针?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01