问题描述
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不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!