C++ Language/Indirection/SmartPointers/RiskFromRawPointers

When implementing one of your functions, you might want to dynamically allocate memory (using ) which you intend to deallocate at the end of your function (using  ). But this will leak memory if an unhandled exception gets thrown during the middle of your function.

Instead of your local variable's type being a raw pointer, it could be a local object variable (initialized as ). Whenever  goes out of scope (even if because of an exception), that local object's destructor will get called. So we can move the responsibility of doing  from our manually-programmed function, into the destructor of this   "smart pointer" class.

C++ provides several built-in smart pointer classes that work like this.

Additional information about the risk from using a raw pointer