简体   繁体   中英

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? 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. 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 . This means that in the absence of the unique_ptr(nullptr_t) constructor, the following code would not compile.

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.


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 .

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. This works because in that comparison, the RHS of == is implicitly convertible to the type of p , because of the nullptr constructor.

Prior to that change, unique_ptr had an implicit conversion operator to a bool-ish type, so the comparison was valid. Merely changing that to a explicit operator bool() would have made the comparison invalid.

A Foo* that happens to have a value of 0 is not type nullptr_t , it is the type Foo* . So, only passing nullptr uses the nullptr_t constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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