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 {
  public:
    A(int i) :m_i(i) {}
    ~A() {}
    int getI() { return m_i; }
  private:
    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;
    vec.resize(5);
    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
Nullptr
Nullptr
Nullptr
Nullptr
Nullptr

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

Answer

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 *