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?

perreal
  • 94,503
  • 21
  • 155
  • 181

2 Answers2

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.

Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35
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.

ThirdOne
  • 1,227
  • 9
  • 13
  • 2
    The reason it works is because of the hidden deleter function stored with the `shared_ptr` 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`. – Jason Jul 24 '12 at 12:29