RAII — Resource Acquisition Is Initialization. Smart pointers are RAII wrappers for dynamic memory.
1// Manual RAII (pre-smart pointers)2void risky() {3 int* p = new int(10);4 throw std::runtime_error("oops"); // Memory leak!5 delete p; // Never reached6}78// RAII with unique_ptr9void safe() {10 auto p = std::make_unique<int>(10);11 throw std::runtime_error("oops"); // OK!12 // p automatically deleted during stack unwinding13}1415// Custom RAII wrapper16template<typename T>17class ScopedPtr {18 T* ptr;19public:20 explicit ScopedPtr(T* p = nullptr) : ptr(p) {}21 ~ScopedPtr() { delete ptr; }22 T* operator->() { return ptr; }23 T& operator*() { return *ptr; }24 // Non-copyable25 ScopedPtr(const ScopedPtr&) = delete;26 ScopedPtr& operator=(const ScopedPtr&) = delete;27 // Movable28 ScopedPtr(ScopedPtr&& other) noexcept : ptr(other.ptr) {29 other.ptr = nullptr;30 }31};
Benefits: