Pointers let objects outlive the scope that created them, be shared without copying, and be used polymorphically. However, there are two common errors when using raw pointers:
- Dangling pointers point to memory that has already been freed:
int* ptr1 = new int{42}; int* ptr2 = ptr1; delete ptr1; *ptr1; // Undefined behaviour. delete ptr2; // Undefined behaviour. - Memory leaks occur when allocated memory is never freed:
while (true) { int* ptr = new int; // delete ptr; }
A smart pointer avoids these errors by using a class to manage the object's lifetime. The destructor frees the object, and the copy operations are deleted to prevent a double free. A minimal smart pointer looks like this:
template <typename T>
class SmartPointer {
public:
SmartPointer(T value) : data(new T{value}) {}
SmartPointer(const SmartPointer&) = delete;
SmartPointer& operator=(const SmartPointer&) = delete;
~SmartPointer() { delete data; }
private:
T* data;
};The standard library has three smart pointers, available from the memory header:
std::unique_ptr#include <memory>: only one smart pointer can own an object.std::shared_ptr#include <memory>: multiple smart pointers can own an object.std::weak_ptr#include <memory>: refers to and does not own an object owned by astd::shared_ptr#include <memory>.
Dan