为什么unique_ptr有删除器作为类型参数而shared_ptr不? [英] Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn't?
问题描述
std :: unique_ptr
模板有两个参数:pointee的类型和删除器的类型。这个第二个参数有一个默认值,所以你通常只写一些 std :: unique_ptr< int>
。
std :: shared_ptr
模板只有一个参数虽然:的pointee的类型。但是您也可以使用自定义删除器与此一个,即使删除类型不在类模板中。通常的实现使用类型擦除技术来执行此操作。
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.
是否有同样的想法不用于 std :: unique_ptr
c $>
Is there a reason the same idea was not used for std::unique_ptr
?
推荐答案
部分原因是 shared_ptr
需要一个明确的控制块反驳计数和坚持一个删除者是不是那么大的交易。 unique_ptr
然而不需要任何额外的开销,并且添加它将不受欢迎 - 它应该是一个零开销类。 unique_ptr
应该是静态的。
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.
您可以随时在顶部添加自己的类型擦除,例如,您可以拥有 unique_ptr< T,std ::函数< void(T *)>>
,我以前做过的事情。
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.
这篇关于为什么unique_ptr有删除器作为类型参数而shared_ptr不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!