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



