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?
Because a
weak_ptr
in concept can only be constructed from anotherweak_ptr
orshared_ptr
. It just doesn't make sense to construct from a raw pointer, whether it'snullptr
or not.You can use a default constructed
weak_ptr
(std::weak_ptr<MyClass>()
) where you are trying to usenullptr
: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?