Jump to content

C++ Language/Indirection/SmartPointers/RiskFromRawPointers

From Wikibooks, open books for an open world

When implementing one of your functions, you might want to dynamically allocate memory (using CRType* poRaw = new CRType;) which you intend to deallocate at the end of your function (using delete poRaw;). 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 CRSmart poSmart(new CRType);). Whenever poSmart 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 delete from our manually-programmed function, into the destructor of this CRSmart "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