Smart pointers are pointers that own the object they point to and automatically destroy the object they point to and deallocate the memory once the pointers go out of scope.
We do not have to manually delete the object like it was the case with the new and delete operators.
Smart pointers are declared in the <memory> header.
We will cover the following smart pointers - unique and shared.
A unique pointer called std::unique_ptr is a pointer that owns an object it points to.
The pointer can not be copied.
Unique pointer deletes the object and deallocates memory for it, once it goes out of scope.
To declare a unique pointer to a simple int object, we write:
#include <iostream> #include <memory> int main() //from w w w.j ava2s . c o m { std::unique_ptr<int> p(new int{ 123 }); std::cout << *p; }
This example creates a pointer to an object of type int and assigns a value of 123 to the object.
A unique pointer can be dereferenced in the same way we as a regular pointer using the *p notation.
The object gets deleted once p goes out of scope, which in this case, is at the closing brace }.
No explicit use of delete operator is required.