[英]Extracting a raw pointer from a shared_ptr
Is it possible to extract a raw pointer from a std::shared_ptr
or std::tr1::shared_ptr
object? 是否可以从std::shared_ptr
或std::tr1::shared_ptr
对象提取原始指针? 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. 上下文是我有一个API,它从用户那里获取原始指针并对该对象进行一些处理。 To make things easier to manage API creates a shared_ptr
out of this raw pointer. 为了使事情更易于管理,请在此原始指针的基础上创建一个shared_ptr
。 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. 无法使用.get()
因为智能指针将必须无限期地保持活动状态。 I would have given back a unique_ptr
but that is not available in tr1
. 我会给一个unique_ptr
但在tr1
不可用。
Basically I want to move the raw pointer out of the shared_ptr. 基本上,我想将原始指针移出shared_ptr。
I think you are searching for the method release()
of shared_ptr
. 我认为您正在搜索shared_ptr
的方法release()
。 Sorry - there is no such method by design. 抱歉-设计上没有这种方法。
Here I found a funny way to do what you want - https://stackoverflow.com/a/13701773/233885 . 在这里,我找到了一种有趣的方式来做您想要的事情-https: //stackoverflow.com/a/13701773/233885 。
You should think about using shared_ptr
again in you context (ownership). 您应该考虑在您的上下文(所有权)中再次使用shared_ptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.