从shared_ptr中提取裸指针 [英] Extracting a raw pointer from a shared_ptr
问题描述
可以从 std :: shared_ptr
或 std :: tr1 :: shared_ptr
object?目的是告诉智能指针对象,我不想要它来管理对象的生命周期。上下文是,我有一个API,从用户取得一个原始指针,并对该对象进行一些处理。为了使事情更容易管理,API创建一个 shared_ptr
这个原始指针。现在,用户可能要求返回对象。在这种情况下,当将处理后的对象返回给用户时,我想要返回原始指针。但是,我还没有找到办法做到这一点。使用 .get()
是不可能的,因为智能指针将必须无限期地保持活着。我将返回 unique_ptr
,但是在 tr1
中不可用。
Is it possible to extract a raw pointer from a std::shared_ptr
or std::tr1::shared_ptr
object? The intent is to tell the smart pointer object that I don't want it to manage the lifetime of the object anymore. The context is that I have an API that takes a raw pointer from users and does some processing on the object. To make things easier to manage API creates a shared_ptr
out of this raw pointer. Now, the user might ask for the object to be returned. In that case, when giving the processed object back to the user I want to give back the raw pointer. However, I have not found a way to do that. Using .get()
is not possible as then the smart pointer will have to be kept alive indefinitely. I would have given back a unique_ptr
but that is not available in tr1
.
基本上,我想将原指针移出shared_ptr。
Basically I want to move the raw pointer out of the shared_ptr.
推荐答案
shared_ptr
的方法 release()
。对不起 - 没有这样的方法设计。
I think you are searching for the method release()
of shared_ptr
. Sorry - there is no such method by design.
在这里,我发现了一个有趣的方式来做你想要的 - http:/ /stackoverflow.com/a/13701773/233885 。
Here I found a funny way to do what you want - http://stackoverflow.com/a/13701773/233885.
您应该考虑再次使用 shared_ptr
在您的上下文(所有权)。
You should think about using shared_ptr
again in you context (ownership).
这篇关于从shared_ptr中提取裸指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!