Search code examples
c++c++11smart-pointers

Will a default-constructed (empty) shared_ptr automatically be initialized to nullptr?


I had read from some blog that a default-constructed (empty) shared_ptr is automatically initialized to nullptr. But could not find any such explicit statement in the standards.

I wrote a small snippet (Linux Compiled) to confirm this:

#include <iostream>
#include <memory>

struct Base;

int main()
{
    std::shared_ptr<Base> p;
    Base* b;

    if (p == nullptr) {
        std::cout << "p IS NULL \n";
    }
    else {
        std::cout << "p NOT NULL \n";
    }

    if (b == nullptr) {
        std::cout << "b IS NULL \n";
    }
    else {
        std::cout << "b NOT NULL \n";
    }

    return 0;
}

Output:

p IS NULL 

b NOT NULL

From this I see that the smart pointers are implicitly assigned nullptr at the time of Declaration. Can somebody confirm this behavior? Is it safe to use a shared_ptr without manually assigning a nullptr to it?


Solution

  • Yes, cppreference tells us that the default constructor is identical to just passing a nullptr to the constructor:

    constexpr shared_ptr() noexcept;                        (1)
    constexpr shared_ptr( std::nullptr_t ) noexcept;        (2)
    

    1-2) Constructs a shared_ptr with no managed object, i.e. empty shared_ptr

    Also from the C++ standard draft for 2017:

    23.11.2.2.1 shared_ptr constructors

    ...

    constexpr shared_ptr() noexcept;
      2 Effects: Constructs an empty shared_ptr object.
      3 Postconditions: use_count() == 0 && get() == nullptr.