Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn't?

狂风中的少年 提交于 2019-12-03 06:28:03

问题


The std::unique_ptr template has two parameters: the type of the pointee, and the type of the deleter. This second parameter has a default value, so you usually just write something like std::unique_ptr<int>.

The std::shared_ptr template has only one parameter though: the type of the pointee. But you can use a custom deleter with this one too, even though the deleter type is not in the class template. The usual implementation uses type erasure techniques to do this.

Is there a reason the same idea was not used for std::unique_ptr?


回答1:


Part of the reason is that shared_ptr needs an explicit control block anyway for the ref count and sticking a deleter in isn't that big a deal on top. unique_ptr however doesn't require any additional overhead, and adding it would be unpopular- it's supposed to be a zero-overhead class. unique_ptr is supposed to be static.

You can always add your own type erasure on top if you want that behaviour- for example, you can have unique_ptr<T, std::function<void(T*)>>, something that I have done in the past.




回答2:


Another reason, in addition to the one pointed out by DeadMG, would be that it's possible to write

std::unique_ptr<int[]> a(new int[100]);

and ~unique_ptr will call the correct version of delete (via default_delete<_Tp[]>) thanks to specializing for both T and T[].



来源:https://stackoverflow.com/questions/6829576/why-does-unique-ptr-have-the-deleter-as-a-type-parameter-while-shared-ptr-doesn

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