Shared void pointers. Why does this work?

后端 未结 2 656
Happy的楠姐
Happy的楠姐 2020-12-15 18:49

To solve a very peculiar problem in my application I need a shared-pointer to allocated data, but to the outside world, the underlying data type should remain hidden.

<
2条回答
  •  死守一世寂寞
    2020-12-15 19:30

    I think the implicit point of the question was that you can't delete by void*, so it seems strange that you can delete through shared_ptr.

    You can't delete an object via a raw void* primarily because it wouldn't know what destructor to call. Using a virtual destructor doesn't help because void doesn't have a vtable (and thus no virtual destructor).

    James McNellis clearly explained why shared_ptr works, but there is something else interesting here: Assuming you follow the documented best practice to always use the following form when invoking new...

    shared_ptr p(new Y);
    

    ...it is not necessary to have a virtual destructor when using shared_ptr. This is true whether T is void, or in the more familiar case where T is a polymorphic base of Y.

    This goes against a long-standing conventional wisdom: That interface classes MUST have virtual destructors.

    The OP's delete (void*) concern is solved by the fact that the shared_ptr constructor is a template that remembers the data type that it needs to destruct. This mechanism solves the virtual destructor problem in exactly the same way.

    So even though the actual type of the object is not necessarily captured in the type of the shared_ptr itself (since T does not have to be the same type as Y), nevertheless, the shared_ptr remembers what type of object it is holding and it performs a cast to that type (or does something equivalent to that) when it comes time to delete the object.

提交回复
热议问题