The purpose of shared_ptr, is there any way to do this?

Is there a way to initialize shared_ptr first with nullptr and after a while get a pointer to the class to it?

//pseudo code std::shared_ptr<MyClass> ptr(nullptr); //and later ptr->assign(new MyClass); 
+4
source share
3 answers

Are you looking for ptr.reset( new MyClass ) ?

+8
source

Use shared_ptr :: reset :

 std::shared_ptr<MyClass> ptr; ptr.reset(new MyClass); 
+3
source

It may not be as efficient as calling reset, but it should also work. Create an inline temporary instance of shared_ptr and assign it.

 std::shared_ptr<MyClass> ptr; ptr = std::shared_ptr<MyClass>(new MyClass); 
+2
source

Source: https://habr.com/ru/post/1390431/


All Articles