---
name: cpp-resource-management
description: "Resource management in C++ using RAII, smart pointers, and the Rule of Five/Zero."
language: cpp
---

# C++ Resource Management

Mastering memory and resource safety in C++ through RAII and modern features.

## Guidelines
- **RAII (Resource Acquisition Is Initialization)**: The core C++ principle for managing resources (memory, files, locks). Resources should be owned by objects whose destructors release them.
- **Smart Pointers**:
  - `std::unique_ptr` for exclusive ownership (default choice).
  - `std::shared_ptr` for shared ownership (use only when necessary).
  - `std::weak_ptr` to break circular dependencies.
- **The Rule of Zero**: Prefer classes that don't manage resources directly (use members that already follow RAII).
- **The Rule of Five**: If you must manage a resource, implement/delete the destructor, copy constructor, copy assignment, move constructor, and move assignment.
- **Avoid Resource Leaks**: Always ensure every resource has a clear owner and a guaranteed cleanup path.
- **Manage Custom Resources**: Use `std::unique_ptr` with custom deleters for non-memory resources (e.g., file handles, C-style API objects).

## Tools & Libraries
- **Valgrind (Memcheck)**: The industry standard for detecting memory leaks and errors.
- **AddressSanitizer (ASan)**: Fast memory error detector built into modern compilers.
- **clang-tidy (modernize-*)**: Automates the transition to smart pointers and other modern features.

## Trigger Scenarios
- When dealing with raw pointers or manual `delete` calls.
- When implementing custom classes that manage system resources.
- When debugging a memory leak or "use-after-free" error.
- When a developer asks about the Rule of Three/Five/Zero.

<!-- synapsis-dsai-managed -->
