Can a unique_ptr take a nullptr value?
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()
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.