17

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 statndards.

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?

1

2 Answers 2

22

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.

7

This is covered in [util.smartptr.shared.const]/3

Ensures: use_­count() == 0 && get() == nullptr.

1
  • @MaxLanghof I've got those mad ninja skills ;) Aug 1, 2019 at 13:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.