Deleter type in unique_ptr vs. shared_ptr [duplicate]

夙愿已清 提交于 2019-11-27 13:39:21

问题


I thought it is very curious when I discovered that the standard defines std::unique_ptr and std::shared_ptr in two totally different ways regarding a Deleter that the pointer may own. Here is the declaration from cppreference::unique_ptr and cppreference::shared_ptr:

template<
    class T,
    class Deleter = std::default_delete<T>
> class unique_ptr;

template< class T > class shared_ptr;

As you can see the unique_ptr "saves" the type of the the Deleter-object as a template argument. This can also be seen in the way the Deleter is retrieved from the pointer later on:

// unique_ptr has a member function to retrieve the Deleter
template<
    class T,
    class Deleter = std::default_delete<T>
>
Deleter& unique_ptr<T, Deleter>::get_deleter();

// For shared_ptr this is not a member function
template<class Deleter, class T>
Deleter* get_deleter(const std::shared_ptr<T>& p);

Can someone explain the rational behind this difference? I clearly favor the concept for unique_ptr why is this not applied to shared_ptr aswell? Also, why would get_deleter be a non-member function in the latter case?


回答1:


Here you can find the original proposal for smart pointers: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1450.html

It answers your question quite precisely:

Since the deleter is not part of the type, changing the allocation strategy does not break source or binary compatibility, and does not require a client recompilation.

This is also useful because gives the clients of std::shared_ptr some more flexibility, for example shared_ptr instances with different deleters can be stored in the same container.

Also, because the shared_ptr implementations needs a shared memory block anyhow (for storing the reference count) and because there alreay has to be some overhead compared to raw pointers, adding a type-erased deleter is not much of a big deal here.

unique_ptr on the other hand are inteded to have no overhead at all and every instance has to embed its deleter, so making it a part of the type is the natural thing to do.



来源:https://stackoverflow.com/questions/27742290/deleter-type-in-unique-ptr-vs-shared-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!