c++c++11shared-ptrsmart-pointersexplicit

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


Solution

  • 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;