why i can't cast nullptr to weak_ptr<>

半世苍凉 提交于 2019-12-04 02:47:14

问题


class MyClass {
public:
     MyClass(std::weak_ptr<MyClass> parent){}
}

i want to do this:

auto newInstance = std::make_shared<MyClass>(nullptr);

or default value of weak_ptr argument is null, such as :

void function(int arg,std::weak_ptr<MyClass> obj = nullptr);

but, what i need is to do this instead:

auto newInstance = std::make_shared<MyClass>(std::shared_ptr<MyClass>(nullptr));

why is that?


回答1:


Because a weak_ptr in concept can only be constructed from another weak_ptr or shared_ptr. It just doesn't make sense to construct from a raw pointer, whether it's nullptr or not.

You can use a default constructed weak_ptr (std::weak_ptr<MyClass>()) where you are trying to use nullptr:

auto newInstance = std::make_shared<MyClass>(std::weak_ptr<MyClass>());
void function(int arg,std::weak_ptr<MyClass> obj = std::weak_ptr<MyClass>());



回答2:


A weak pointer's primary purpose is usually to know whether an object that might be destroyed by other code still exists. How could a weak pointer constructed from an ordinary pointer possibly know whether the object still exists? Can you even imagine a way this could possibly work?



来源:https://stackoverflow.com/questions/11281909/why-i-cant-cast-nullptr-to-weak-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!