43

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Zhen
  • 4,171
  • 5
  • 38
  • 57

2 Answers2

64

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.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • 1
    I see. BTW, only nullptr has nullptr_t, thats the way it's done, isn't? – Zhen Feb 25 '13 at 15:58
  • 2
    @Zhen: The standard does not specify this. You could create a variable of type `nullptr_t`, but I doubt you will ever need to do that. – Andy Prowl Feb 25 '13 at 16:03
3

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()
mrgloom
  • 20,061
  • 36
  • 171
  • 301