jeudi 1 août 2019

Is a default-constructed (empty) shared_ptr automatically 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.

std::shared_ptr<Base> p;

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

Base* b;

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

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?

Aucun commentaire:

Enregistrer un commentaire