Smart pointer types:
Usually a class template.
Behaves syntactically in a similar way to pointers.
Has the special member functions, for construction, destruction, moving and copying, defined to maintain certain invariants.
Roughly they make sure we don’t run into problem with: Memory leaks, use-after-freeing, heap corruption via pointer arithmetic (we free the wrong location).
They automatically delete the object to which theypoint.Standard smart pointers ...
There are two standard smart pointer types from C++11, defined in the memory header. The first, std::unique_ptr<T>, defines a pointer that owns the thing pointed to.
So if you call the destructor for the unique_ptr, the thing pointed too will be destroyed too.
As would seem sensible, at any time there can only be a single unique_ptr to a given object.
There is a version std::unique_ptr<T,D> with D being the defined deleter, defaulting to std::default_delete<T>, which calls operator delete.
Whenever we allocate a resource, we initialize a unique_ptr to manage it. Avoid using new directly...The second is for managing situations where we want multiple references to the same object...
std::shared_ptr<T>
They can be set up using statements like:
shared_ptr<string> p1;
shared_ptr<list<int>> p2;
The shared_ptr records how many references there are to an object and destroys the object iff the last reference to the object is being destroyed.
And in doing so tidies up the memory.