Home > database >  Why `shared_ptr<int> p; p=nullptr;` compiles?
Why `shared_ptr<int> p; p=nullptr;` compiles?

Time:03-13

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 that why std::make_shared<int>(1); p = nullptr; compiles?

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

CodePudding user response:

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 won't work:

auto p = std::make_shared<int>(1);
p = NULL;
int * a = nullptr;
p = a;
  • Related