default value of a unique_ptr

I am having difficulty understanding default value of unique_ptr.
From the cpp reference I see that there are two constructors of unique_ptr that says it owns nothing
Does nothing mean nullptr?

constexpr unique_ptr() noexcept;
constexpr unique_ptr( std::nullptr_t ) noexcept;

I created an small example below. If I check for nullptr, it returns true. Is this behavior guaranteed?

#include <memory>
#include <vector>
#include <iostream>

class A {
    A(int i) :m_i(i) {}
    ~A() {}
    int getI() { return m_i; }
    int m_i;

int main() {
    std::unique_ptr<A> a;
    if(a == nullptr) {
     std::cout << "A is nulln";   
    std::vector<std::unique_ptr<A>> vec;
    for(size_t i = 0; i < vec.size(); i++) {
        if(vec[i] == nullptr) {
            std::cout << "Nullptr" << std::endl;   
    return 0;

O/p of the above code in my system (gcc) is

A is null

If I check for null on an uninitialized unique_ptr, is it guaranteed that it will be nullptr? Or Is it implementation defined?


For these two constructor overloads:

constexpr unique_ptr() noexcept;
constexpr unique_ptr(std::nullptr_t) noexcept;

The documentation says that these two constructors above create a std::unique_ptr object that owns nothing.

Now, by looking at the documentation of std::unique_ptr‘s get() member function:

Returns a pointer to the managed object or nullptr if no object is owned.

Since the std::unique_ptr objects that are created through any of those two constructors own nothing, we conclude that get() returns nullptr for these std::unique_ptr objects.

Leave a Reply

Your email address will not be published. Required fields are marked *