Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a shared_ptr, is there a way to do it?

Tags:

c++

is there a way of first initialize shared_ptr with nullptr and after some time assing a pointer to a class to it?

//pseudo code
std::shared_ptr<MyClass> ptr(nullptr);  
//and later
ptr->assign(new MyClass);
like image 244
smallB Avatar asked Dec 12 '22 06:12

smallB


2 Answers

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

like image 84
Andrew Durward Avatar answered Feb 09 '23 19:02

Andrew Durward


Use shared_ptr::reset:

std::shared_ptr<MyClass> ptr;

ptr.reset(new MyClass);
like image 39
hmjd Avatar answered Feb 09 '23 20:02

hmjd