问题描述:

This question already has an answer here:

  • Why does unique_ptr take two template parameters when shared_ptr only takes one?

    1 answer

网友答案:

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.

相关阅读:
Top