Why does unique_ptr have a nullptr_t constructor?

I do not understand what are the advantages.

If I have:

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

Is the nullptr_t constructor in this situation? Or only if you run:

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

Thanks!

Below is a discussion that will allow you to pass to nullptr_t, otherwise it will not be compiled, since it will not be used to enter a type pointer. So my question may be, why is he not throwing?

+6
source share
3 answers

A possible reason is that the unique_ptr constructor, which takes a unique_ptr::pointer argument, is explicit . This means that in the absence of the unique_ptr(nullptr_t) constructor, the following code will not compile.

 std::unique_ptr<int> intp = nullptr; 

Since a unique_ptr intended for a lightweight smart pointer that closely mimics the semantics of a raw pointer, it is advisable that the code above be compiled.


In the first example, the nullptr_t constructor nullptr_t not called because the argument type is Foo* , although its value is nullptr .

+12
source

The original sentence, which is added to the constructor to be added, here explains the usage example: it is intended to compile if (p == 0) . This works because in this comparison, RHS == implicitly converted to type p due to the nullptr constructor.

Prior to this change, unique_ptr had an implicit conversion operator to type bool-ish, so the comparison was valid. Simply changing this parameter to explicit operator bool() would make the comparison invalid.

+2
source

A Foo* , which has a value of 0 , is not a nullptr_t type, it is a Foo* type. So, only passing nullptr uses the nullptr_t constructor.

+1
source

Source: https://habr.com/ru/post/974340/


All Articles