简体   繁体   English

为什么unique_ptr有一个nullptr_t构造函数?

[英]Why does unique_ptr have a nullptr_t constructor?

It isn't clear to me what the benefits are. 我不清楚它的好处是什么。

If I have: 如果我有:

Foo* foo = nullptr;
std::unique_ptr<Foo> unique_foo(foo);

Is the nullptr_t constructor called in that situation? 在那种情况下是否调用了nullptr_t构造函数? Or only if you do: 或者只有你这样做:

std::unique_ptr<Foo> unique_foo(nullptr);

Thanks! 谢谢!

There is some discussion here which is to allow you to passing in nullptr_t, otherwise it won't compile since it won't cast to type pointer. 有一些讨论, 这里是让你来传递nullptr_t,否则将无法编译,因为它不会转换为指针类型。 So my question may be why it doesn't cast? 所以我的问题可能是为什么它不投?

A possible reason is that the unique_ptr constructor that takes a unique_ptr::pointer argument is explicit . 一个可能的原因是带有unique_ptr::pointer参数的unique_ptr构造函数是explicit This means that in the absence of the unique_ptr(nullptr_t) constructor, the following code would not compile. 这意味着在没有unique_ptr(nullptr_t)构造函数的情况下,以下代码将无法编译。

std::unique_ptr<int> intp = nullptr;

Since a unique_ptr is intended to be a lightweight smart pointer that closely imitates raw pointer semantics, it is desirable to have the above code compile. 由于unique_ptr旨在成为一个轻量级智能指针,它非常模仿原始指针语义,因此需要编译上述代码。


In your first example the nullptr_t constructor is not called because the type of the argument is Foo* , even though its value is nullptr . 在第一个示例中,未调用nullptr_t构造函数,因为参数的类型为Foo* ,即使其值为nullptr

The original proposal that lead to the constructor being added is here , and explains the use case: it's intended to make if (p == 0) compile. 导致添加构造函数的原始提议在这里 ,并解释用例:它旨在使if (p == 0)编译。 This works because in that comparison, the RHS of == is implicitly convertible to the type of p , because of the nullptr constructor. 这是有效的,因为在该比较中,由于nullptr构造函数, ==的RHS可隐式转换为p的类型。

Prior to that change, unique_ptr had an implicit conversion operator to a bool-ish type, so the comparison was valid. 在此更改之前, unique_ptr具有bool-ish类型的隐式转换运算符,因此比较有效。 Merely changing that to a explicit operator bool() would have made the comparison invalid. 仅仅将其更改为explicit operator bool()会使比较无效。

A Foo* that happens to have a value of 0 is not type nullptr_t , it is the type Foo* . Foo*碰巧具有值0不是类型nullptr_t ,它是类型Foo* So, only passing nullptr uses the nullptr_t constructor. 因此,只传递nullptr使用nullptr_t构造函数。

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

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