C++ Programming Tips: Managing Resources with Smart Pointers

Resources refer to entities that, once used, must be returned to the system. For example, dynamically allocated memory using “new” needs to be returned to the system with “delete”, as well as resources like bitmaps and brushes.

1. Disadvantages of Manual Resource Management

Consider the following example:

C++ Programming Tips: Managing Resources with Smart Pointers

We “new” a resource and return it to the system with “delete” at the end of the function, which seems fine. However, note the “…” part; if a “return” occurs or an exception is thrown, many situations can lead to “delete” not being executed, resulting in a memory leak.

2. Managing Resources with Smart Pointers

“std::auto_ptr” is a smart pointer that uses “delete” in its destructor to release the managed resource. Therefore, we can modify the above code as follows:

C++ Programming Tips: Managing Resources with Smart Pointers

At this point, regardless of what happens in the function, when exiting the function, the compiler will call the destructor of “std::auto_ptr”, which will “delete” the managed resource.

One issue is that “std::auto_ptr” destroys the pointed resource upon destruction. If multiple “std::auto_ptr” instances point to the same resource, the resource will be destroyed multiple times, leading to errors. Therefore, “std::auto_ptr” has a very special property: when copied using the “copying function”, the copied instance will point to “null”, and the copy will gain the sole ownership of the resource.

3. Different Types of Smart Pointers

Due to the special nature of the “copying function” of “std::auto_ptr”, it is not suitable for all situations. The reference-counted smart pointer “std::tr1::shared_ptr” can solve this problem, allowing multiple pointers to point to the same resource, and the resource is only destroyed when all “std::tr1::shared_ptr” instances pointing to it are destructed.

4. Issues to Note

This technique suggests using smart pointers to manage resources; however, this smart pointer does not necessarily have to be a true smart pointer; it can also be an object similar to a smart pointer. Moreover, the previously mentioned smart pointers are not perfect; for instance, “std::tr1::shared_ptr” cannot break circular references (mutual pointing issues), and both use “delete” instead of “delete[]”, etc.

Leave a Comment