从 shared_ptr 中分离一个指针?

Detach a pointer from a shared_ptr?(从 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 中分离一个指针?

基础教程推荐