Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why i can't cast nullptr to weak_ptr<>

Tags:

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?

like image 262
uray Avatar asked Jul 01 '12 12:07

uray


People also ask

Can you cast a Nullptr?

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.

Can a weak_ptr point to a Unique_ptr?

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.

Can you static cast a Nullptr?

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.

What is weak_ptr in C++?

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.


1 Answers

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>()); 
like image 60
David Avatar answered Sep 22 '22 14:09

David