Can a unique_ptr take a nullptr value?

36,243

Solution 1

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.

Solution 2

More common case:

#include <iostream>
#include <string>
#include <memory>

class A {
public:
    A() {std::cout << "A::A()" << std::endl;}
    ~A() {std::cout << "A::~A()" << std::endl;}
};

class B {
public:
    std::unique_ptr<A> pA;
    B() {std::cout << "B::B()" << std::endl;}
    ~B() { std::cout << "B::~B()" << std::endl;}
};

int main()
{
    std::unique_ptr<A> p1(new A());

    B b;
    b.pA = std::move(p1);
}

Output:

A::A()
B::B()
B::~B()
A::~A()

This code example can be non-intuitive:

#include <iostream>
#include <string>
#include <memory>

class A {
public:
    A() {std::cout << "A::A()" << std::endl;}
    ~A() {std::cout << "A::~A()" << std::endl;}
};

class B {
public:
    std::unique_ptr<A> pA;
    B() {std::cout << "B::B()" << std::endl;}
    ~B() 
    {
        if (pA)
        {
            std::cout << "pA not nullptr!" << std::endl;
            pA = nullptr; // Will call A::~A()
        }
        std::cout << "B::~B()" << std::endl;
    }
};

int main()
{
    std::unique_ptr<A> p1(new A());

    B b;
    b.pA = std::move(p1);
}

Output:

A::A()
B::B()
pA not nullptr!
A::~A()
B::~B()
Share:
36,243
Zhen
Author by

Zhen

I'm a Game Programmer at soul but currently I work as System Administrator. To see me rant: http://malcodigo.blogspot.com To see me walk: http://zhenpaseando.blospot.com To just see me: Napoli, Italia. My best known work: Doodle Hex for Nintendo DS, Cell &amp; Love for Android and Altamira II Supercomputer for the RES.

Updated on July 16, 2020

Comments

  • Zhen
    Zhen almost 4 years

    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?