1

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.

Basically I want to move the raw pointer out of the shared_ptr.

341008
  • 9,862
  • 11
  • 52
  • 84
  • Could you make an example with code? I don't quite understand why you would want to return a pointer to the user. – Shoe Apr 09 '14 at 13:07
  • Is the pointer to a class you have control over, or derived from a class you have control over? – aschepler Apr 09 '14 at 13:08
  • @Jefffrey , unfortunately, a code sample would be too complicated. Just realizing how difficult it is to explain, I am beginning to think I need to change my design :) – 341008 Apr 09 '14 at 13:18
  • @341008, yeah, it looks like you should. :) – Shoe Apr 09 '14 at 13:20

1 Answers1

1

I think you are searching for the method release() of shared_ptr. 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.

You should think about using shared_ptr again in you context (ownership).

Community
  • 1
  • 1
  • Yup, I was looking for a `release()` method. The answer suggested in that post is probably too risky for a non-expert like me. I don't want to have to track down bugs in that :). I think I will have to rethink my design. Thanks anyway. – 341008 Apr 09 '14 at 13:19