Search code examples
c++c++11pointersunique-ptrnullptr

Can a unique_ptr take a nullptr value?


Is this code fragment valid? :

unique_ptr<A> p(new A());
p = nullptr;

That is, can I assign nullptr to a unique_ptr ? or it will fail?

I tried this with the g++ compiler and it worked, but what about other compilers?


Solution

  • It will work.

    From Paragraphs 20.7.1.2.3/8-9 of the C++11 Standard about the unique_ptr<> class template:

    unique_ptr& operator=(nullptr_t) noexcept;

    Effects: reset().

    Postcondition: get() == nullptr

    This means that the definition of class template unique_ptr<> includes an overload of operator = that accepts a value of type nullptr_t (such as nullptr) as its right hand side; the paragraph also specifies that assigning nullptr to a unique_ptr is equivalent to resetting the unique_ptr.

    Thus, after this assignment, your A object will be destroyed.