+ 1

Smart pointer - shared_ptr, unique_ptr etc.

Can someone simply explain how these pointers work like? With a simple example if possible. I find it difficult to find it on the web.

1st Nov 2016, 3:43 PM
Wojciech SkibiƄski
Wojciech SkibiƄski - avatar
2 Answers
+ 2
I'll try to keep it brief. unique_ptr is the single owner of an object: auto p = std::make_unqiue <int>(1); No need to call delete on it, when it goes out of scope, memory is freed. For shared_ptr, same concept except it can have multiple owners. auto p = std::make_shared <int>(2); auto p2 = p; // Points to memory of p The memory will only be freed when both go out of scope. Only use shared_ptr if multiple objects must hold on to the data.
6th Jan 2017, 10:18 PM
unixunited
unixunited - avatar
+ 1
its more than just memory management tool, it also give clarity to your code. imagine this function declaration widget* createWidget(...); it has one major problem, you must know what to do with returned object. do you need to take care and delete object, when it is no longer needed, or maybe this function takes care of memory itself. with the help of unique_ptr or shared_ptr you know exactly what this function is doing. if declaration looks like this. unique_ptr<widget> createWidget(...) you dont need to worry about who needs to delete this object. if createWidget is part of library that keeps track of all created objects it will return shared_ptr<widget> for you :) i strongly encourage to avoid new/delete as much as possible, it will make your life much simpler.
17th Apr 2017, 4:50 PM
Mindaugas Vinkelis
Mindaugas Vinkelis - avatar