Smart Pointer (C++)
A smart pointer is an object that manages a dynamically allocated resource and frees it automatically when no longer needed. It prevents memory leaks by handling delete for you.
C++
The two main smart pointers are std::unique_ptr (sole ownership of a resource) and std::shared_ptr (shared ownership counted by references). Both live in the <memory> header.
Smart pointers are an application of RAII: the resource is released in the smart pointer's destructor when it goes out of scope. Modern C++ strongly prefers them over raw new/delete.
Syntax
std::unique_ptr<T> p = std::make_unique<T>(args);Examples
C++
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> p = std::make_unique<int>(42);
std::cout << *p << std::endl;
return 0;
}Output:
42