简体   繁体   English

为什么unique_ptr不能推断出删除器的类型?

[英]Why can't unique_ptr infer the type of the deleter?

Let's say I want to use a custom deleter with an unique_ptr: 假设我想使用带有unique_ptr的自定义删除器:

void custom_deleter(int* obj)
{
    delete obj; 
}

Why do I have to write this: 为什么我要写这个:

std::unique_ptr<int, void(*)(int*)> x(new int, custom_deleter);

instead of this: 而不是这个:

std::unique_ptr<int> x(new int, custom_deleter); //does not compile

?

Can't the type of the deleter be inferred? 不能推断出删除器的类型吗?

For unique_ptr , the deleter is part of the type: 对于unique_ptr ,删除器是类型的一部分:

template <
    class T,
    class Deleter = std::default_delete<T>
> class unique_ptr;

As such, when you're constructing an object, you need to specify its type. 因此,在构建对象时,需要指定其类型。 The line you're writing: 你写的这行:

std::unique_ptr<int> x(new int, custom_deleter);

is equivalent to: 相当于:

std::unique_ptr<int, std::default_delete<int> > x(new int, custom_deleter);

And you cannot construct a std::default_delete<int> from custom_deleter . 而且你不能从custom_deleter构造一个std::default_delete<int>

The only way to infer the deleter type is to use template deduction on that part too: 推断删除类型的唯一方法是在该部分上使用模板推导:

template <typename T, typename Deleter>
std::unique_ptr<T, Deleter> make_unique_ptr(T* ptr, Deleter deleter) {
    return std::unique_ptr<T, Deleter>(ptr, deleter);
}

It cannot infer the type of the deleter, because unique_ptr by default has no state devoted to a deleter: the default deleter is stateless. 它无法推断删除器的类型,因为默认情况下unique_ptr没有专门用于删除器的状态:默认删除器是无状态的。

In your case, the deleter needs a pointer's worth of state, so it cannot 'fit' within the std::unique_ptr 's state (which is just a pointer to a T ). 在你的情况下,删除器需要一个指针的状态值,因此它不能“适应” std::unique_ptr的状态(它只是指向T的指针)。

This makes unique_ptr a lightweight, nearly cost-free replacement for an owning pointer. 这使得unique_ptr成为拥有指针的轻量级,几乎无成本的替代品。

Deductin could be done, but it would have to change the type of the resulting unique_ptr . 可以完成Deductin,但必须更改结果unique_ptr的类型。

In comparison, shared_ptr always has state capacity for a deleter, two different atomic counters, and a pointer to value. 相比之下, shared_ptr总是具有删除器的状态容量,两个不同的原子计数器和一个指向值的指针。 It is heavier weight, and not a cost-free replacement for a pointer. 它的重量更重,而且不是指针的免费替代品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM