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?
For the first function, yes, you can cast the returned std::nullptr_t to another pointer type (you don't even need a cast to do the conversion, it will happen implicitly) but that's probably not something you ever want to do.
You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case.
In the end, the reason static_cast on NULL pointer crashes, is because a static_cast with inheritance might requires a bit of pointer arithmetic form the compiler. This depend on how the compiler actually implement inheritance. But in case of multiple inheritance, it doesn't have a choice.
Defined in header <memory> template< class T > class weak_ptr; (since C++11) std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With