Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 277
Boanerges Avatar asked Aug 01 '19 13:08

Boanerges


2 Answers

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.

like image 83
ruohola Avatar answered Nov 15 '22 11:11

ruohola


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

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

like image 38
NathanOliver Avatar answered Nov 15 '22 12:11

NathanOliver