9

I have a structure:

struct Params {
   std::shared_ptr<void> user_data;
   /* ... */
};

I want to use it like this:

int main() {
  std::shared_ptr<SpecializedParams> sp(new SpecializedParams(100));
  Params params;
  /* ... */
  params.user_data = std::static_pointer_cast<void>(sp); 
  /* ... */
  std::shared_ptr<SpecializedParams> sp2 = 
    std::static_pointer_cast<SpecializedParams>(
      params.user_data
    );
  /* ... */
  return 0;
}

Is this valid and safe?

5
  • What is params in main block ? Jul 24, 2012 at 4:40
  • You can't delete a void pointer, so your code shouldn't even compile.
    – Kerrek SB
    Jul 24, 2012 at 5:52
  • 3
    @KerrekSB shared pointers to void are certainly valid. See here for more details: stackoverflow.com/questions/5913396/… Jul 24, 2012 at 6:26
  • @MichaelAnderson: Oh OK, the deleter is deduced from the argument, not from the pointee type - interesting!
    – Kerrek SB
    Jul 24, 2012 at 6:55
  • 1
    You might want to use static_pointer_cast without std::. It will still work due to argument-dependent lookup.
    – sellibitze
    Jul 25, 2012 at 9:01

2 Answers 2

8

The code, that actual deletes the shared object is determined when the shared pointer is created (that's why you need a complete type, when constructing the shared_ptr and not, when destructing the shared_ptr). Thus even when your shared_ptr is the last pointer that points to your SpecializedParams object, the object will get correctly destroyed.

3

This should be safe as the void casted item is a shared_ptr too. It will add a reference to the existing element and it will not be released until the void casted item goes away.

1
  • 2
    The reason it works is because of the hidden deleter function stored with the shared_ptr<T> object ... Otherwise simply calling delete on a void pointer will not correctly deallocate the memory resources of the object being managed by the shared_ptr<T>.
    – Jason
    Jul 24, 2012 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.