Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does shared_ptr<int> p; p=nullptr; compile?

Since the constructor of std::shared_ptr is marked as explicit one, so expressions like auto p = std::make_shared<int>(1); p = new int(6); is wrong.

My question is why does std::make_shared<int>(1); p = nullptr; compile?

Here is the aforementioned code snippet:

#include <memory>
#include <iostream>

int main()
{
    auto p = std::make_shared<int>(1);

    //p = new int(6);

    p = nullptr;

    if(!p)
    {
        std::cout << "not accessable any more" << std::endl;
    }

    p.reset();
}

Such code is seen at std::shared_ptr: reset() vs. assignment

like image 783
John Avatar asked Sep 15 '25 12:09

John


1 Answers

The raw pointer constructor is explicit to prevent you accidentally taking ownership of a pointer. As there is no concern taking ownership of nullptr the constructor taking std::nullptr_t is not marked explicit.

Note that this only applies to nullptr these other assignments of a null pointer might not work (depending on your compiler):

auto p = std::make_shared<int>(1);
p = NULL;
int * a = nullptr;
p = a;
like image 152
Alan Birtles Avatar answered Sep 17 '25 02:09

Alan Birtles