What I Learned from Scott Meyers' Effective C++, Part 3

Chapter 3: Resource Management

In my previous chapter, we discussed Constructors, Destructors, and Assignment Operators. In this chapter, we'll talk about what I learned in chapter 3 of the book, items 13 to 17.

Item 13: Use objects to manage resources

RAII, Resource acquisition is initialization is a commonly used idea in C++. Acquired resources are immediately initialized in almost all correct usages. Using objects to manage your resources enforces this behaviour. RAII approach helps avoid memory leaks in your code by acquiring resources in your constructor and releasing them in the destructor since objects that go out of scope automatically call their destructors in C++. Smart pointers such as unique_ptr, shared_ptr and weak_ptr are commonly used resource management objects introduced in C++11.

Item 14: Think carefully about copying behaviour in resource managing classes

The copying behaviour of your resources defines the copying behaviour of your resource-managing classes. Be aware of your requirements and disallow copying if necessary. Certain smart_pointers like the shared_ptr and weak_ptr allow for flexible resource sharing behaviours. Understand the implementations of these classes and use them accordingly if your design requires such utilities.

Item 15: Provide access to raw resources in resource managing classes

It is common to use libraries that require direct access to your resources such as a raw pointer. It is important that your RAII classes provide access to your raw data. Implicit conversion from your resource class to raw pointers can be easier for client code to use however it will be safer to use explicit conversions.

Item 16: Use the same form in corresponding uses of new and delete

Acquiring memory through the use of the new keyword in C++ is common and the sensible action is to release that memory back to the operating system with the delete keyword when you no longer need it. However, allocating an array of types through new[] requires you to use delete[] in order to properly free your allocated memory. Incorrectly releasing such memory with the delete keyword only will lead to memory leaks.

Item 17: Store newed objects in smart pointers in standalone statements.

It is possible to lose access to allocated memory when the new keyword is called with different calls within the same statement. This can cause subtle memory leaks within your system as exceptions occur in such statements. Therefore, it is safest to store your newed objects in smart pointers using statements that call the new operator.

That's it for this chapter, next article will be about Chapter 4, Designs and Declarations