12.1.4. Smart Pointers and Exceptions


In § 5.6.2 (p. 196) we noted that programs that use exception handling to continue processing after an exception occurs need to ensure that resources are properly freed if an exception occurs. One easy way to make sure resources are freed is to use smart pointers.

When we use a smart pointer, the smart pointer class ensures that memory is freed when it is no longer needed even if the block is exited prematurely:

void f(){    shared_ptr<int> sp(new int(42)); // allocate a new object   // code that throws an exception that is not caught inside f} // shared_ptr freed automatically when the function ends

When ...

Get C++ Primer, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.