为什么unique_ptr需要两个模板参数,当shared_ptr只需要一个? [英] Why does unique_ptr take two template parameters when shared_ptr only takes one?
问题描述
unique_ptr 和 shared_ptr 接受一个自定义析构函数来调用他们自己的对象。但是在 unique_ptr
的情况下,析构函数作为类的模板参数传递,其中 shared_ptr
Both unique_ptr and shared_ptr accept a custom destructor to call on the object they own. But in the case of unique_ptr
, the destructor is passed as a template parameter of the class, wherease the type of shared_ptr
's custom destructor is to be specified as a template parameter of the constructor.
template <class T, class D = default_delete<T>>
class unique_ptr
{
unique_ptr(T*, D&); //simplified
...
};
和
template<class T>
class shared_ptr
{
template<typename D>
shared_ptr(T*, D); //simplified
...
};
我看不出为什么会有这样的差别。
I can’t see why such difference. What requires that?
推荐答案
如果你提供的删除作为模板参数(如 unique_ptr
)它是类型的一部分,你不需要在这个类型的对象中存储任何额外的东西。
如果deleter作为构造函数的参数传递(如 shared_ptr
),则需要将其存储在对象中。这是额外的灵活性的代价,因为你可以为同一类型的对象使用不同的删除器。
If you provide the deleter as template argument (as in unique_ptr
) it is part of the type and you don't need to store anything additional in the objects of this type.
If deleter is passed as constructor's argument (as in shared_ptr
) you need to store it in the object. This is the cost of additional flexibility, since you can use different deleters for the objects of the same type.
我想这是原因: unique_ptr
应该是非常轻量级的对象,零开销。用每个 unique_ptr
存储删除器可以使其大小增加一倍。因为人们会使用好的旧原始指针,而这是错误的。
I guess this is the reason: unique_ptr
is supposed to be very lightweight object with zero overhead. Storing deleters with each unique_ptr
could double their size. Because of that people would use good old raw pointers instead, which would be wrong.
另一方面, shared_ptr
不是那么轻量级,因为它需要存储引用计数,所以存储自定义删除程序看起来好像是好的交换。
On the other hand, shared_ptr
is not that lightweight, since it needs to store reference count, so storing a custom deleter too looks like good trade off.
这篇关于为什么unique_ptr需要两个模板参数,当shared_ptr只需要一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!