0

How can I Replace raw pointers with Smart pointers?

specifically when work with some functions as belong to external library. It will be very clear if it presented as comprehensive example.

6th Sep 2019, 10:28 PM
Alireza Abbasi
Alireza Abbasi - avatar
3 odpowiedzi
+ 3
Just replace "T* p = new T(...);" with "std::unique_ptr<T> p( new T(...) );" // or shared_ptr or "p.reset( new T(...) );" after initialization and functions that expect a T* simply use "p.get()". The rest is pretty much the same as a raw pointer. For example: void f( int* p ){ *p = 4; } int main() { int* p = new int( 5 ); f( p ); std::cout << *p; delete p; } Becomes: void f( int* p ){ *p = 4; } int main() { std::unique_ptr<int> p( new int( 5 ) ); // Don't use = f( p.get() ); std::cout << *p; }
6th Sep 2019, 10:49 PM
Dennis
Dennis - avatar
+ 2
You'd put them into a separate variable and then get that pointer's address like. " std::unique_ptr<int> p; int* p_tmp = p.get(); foo( &p_tmp, ptr_d.get() ); " If foo assigns a new address you'd have to update the unique_ptr too with "p.reset( p_tmp );" Maybe even with "p.reset( std::exchange( p_tmp, nullptr ) );" to cleanup p_tmp as well by setting it to nullptr if the object is move constructible. Not sure if there are better ways. You probably want to avoid ** as much as possible. :)
8th Sep 2019, 10:00 AM
Dennis
Dennis - avatar
+ 1
Thanks Dennis. And one more thing, what about pointer to pointer arguments? void foo(int** ptr, double* ptr_d) ; according to your answer preceding statement convert to: unique_ptr <int> ptr_d { make_unique <int>(9)} ; void (???, ptr_d. get()) ;
7th Sep 2019, 7:07 PM
Alireza Abbasi
Alireza Abbasi - avatar