Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting shared_ptr<T> to shared_ptr<void>

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?

like image 340
perreal Avatar asked Jul 24 '12 04:07

perreal


1 Answers

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.

like image 58
Torsten Robitzki Avatar answered Sep 28 '22 06:09

Torsten Robitzki