[C++][Chap. 3] Resource Management

[content]

Items 13: Using objects to manage resource

DO: Resources are acquired and immediately turned over to resource-managing objects. Resource-managing object use their destructors to ensure that resources are released.

WHY: RAII (Resource Acquisition Is Initialization) objects can prevent memory leak (using destructors). unique_ptr and shared_ptr are RAII objects.

Items 14: Think carefully about copying behavior in resource-managing classes

DO: There are different ways to handling copying resource-managing objects.
1. Prohibit copying.
2. Reference-count the underlying resource.
3. Copy the underlying resource. (deep copy)
4. Transfer ownership of the underlying resource. (rare case, behaves like move semantic)

WHY: Copying resource-managing objects entail copying underlying resources.

Items 15: Provide access to raw resource in resource manage class

DO: You can provide a Get function to return the raw pointer to the resource.

WHY: The RAII class doesn’t exist to encapsulate something, but to ensure the resource is released.

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

DO: Be careful if you have call new for a pointer to array, you need to call the delete on the array pointer. Be careful of the typedef case.

typedef std::string AddressLines[4];
std::string *pal = new AddressLines; // same as new string[4];
delete pal;  // undefined!
delete[] pal; // fine

Items 17: store new-ed objects in smart pointers in standalone statements

DO: Declare and define smart pointers in a standalone statement.

ProcessWidget(std::shared_ptr<Widget>(new Widget), priority());

WHY: C++ does not specify a fixed evaluation order for function parameters. The execution order for function parameters above could be,
1. new widget
2. priority()
3. std::shared_ptr

Leave a Reply

Your email address will not be published. Required fields are marked *