Today I was asked about smart pointers in C++, and I can't find anywhere useful information about it..
Please, can someone tell: What is smart pointers? When do you need it? Do you have any example where smart pointers is actually useful?
Thank you!
Primarily, smart pointers help you to:
A good example of where smart pointers are useful:
A vector of pointers to objects. By making it a vector of shared pointers, for example, the objects will automatically be deallocated when the vector is destroyed and/or objects are removed. This automates object lifetime management and helps the user of the container avoid memory leaks.
Excerpt from Boost Smart Pointers (smart_ptr) lib:
Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.
Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for deletion of the object when it is no longer needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With