liveBook · Manning

Resource acquisition is initialization

As explained in 100 C++ Mistakes and How to Avoid Them

RAII is a C++ resource-management idiom that binds resource lifetime to the lifetime of an object.

RAII binds a resource’s lifetime to an object’s lifetime. A constructor acquires the resource, and the destructor releases it automatically, including during exception paths. section 10.0 section 10.5

The mistake is managing resources with scattered raw-pointer cleanup. Copying an owning pointer can create two apparent owners, causing leaks, double deletion, or undefined behavior; exceptions make manual cleanup harder still. section 2.8 section 10.4

Use ownership-specific RAII types:

  • Use std::unique_ptr for exclusive ownership and transfer ownership explicitly with std::move. section 2.8
  • Use std::shared_ptr when multiple references share one resource; prefer std::make_shared over direct new where possible. section 2.9
  • For legacy code, replace manual cleanup incrementally and test both normal and exceptional paths. section 10.6

Replacing a double-delete bug

A raw-pointer version copies b1 into b2 and deletes both. The RAII version stores the buffer in std::unique_ptr<int[]> and transfers the owning Buffer with auto b2 = std::move(b1); cleanup then occurs automatically. section 2.8

Listing 2.16 Implementing exclusive ownership using unique_ptr
struct Buffer {
private:
    std::unique_ptr<int[]> data;                            #1
public:
    Buffer() : data(std::make_unique<int[]>(10)) {}         #2
};
 
int main() {
    auto b1 = std::make_unique<Buffer>();                   #3
    auto b2 = std::move(b1);                                #4
    return 0;
}

Shows an exclusive resource managed by std::unique_ptr and moved between owners. section 2.8

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains ownership, destructors, exceptions, and smart-pointer implementations, while deferring resource-specific management classes.
Examples
Uses buffers, deques, grades, files, and student objects to contrast raw-pointer cleanup with RAII.
What it assumes
Assumes familiarity with pointers and dynamic allocation while teaching ownership, cleanup pairing, and exception safety.
What you can do after
Apply it via std::unique_ptr and std::shared_ptr to automate cleanup and express ownership.
How it connects
Connects constructors, destructors, exceptions, ownership, unique_ptr, shared_ptr, and move semantics.

Also explained in

Compare how 4 books explain resource acquisition is initialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.