C++ Idioms and Patterns
Modern C++ (17/20/23) rewards RAII, value semantics, and zero-cost abstractions. Lean into the type system and smart pointers. Idiomatic C++ = safe, deterministic, performant.
Scope: C++ coding idioms. Test naming: .agents/rules/testing-strategy.md.
Ownership and Memory
RAII — resources tied to object lifetime. No manual new/delete.
std::unique_ptr for exclusive ownership, std::shared_ptr only when sharing is necessary.
Move semantics — prefer moving over copying for expensive types.
Rule of Five/Zero:
// ✅ Rule of Zero — let compiler-generated defaults work
class TaskService {
std::unique_ptr<TaskStorage> storage_;
std::shared_ptr<Logger> logger_;
public:
// No destructor, copy/move constructors needed — smart pointers handle it
explicit TaskService(std::unique_ptr<TaskStorage> storage, std::shared_ptr<Logger> logger)
: storage_(std::move(storage)), logger_(std::move(logger)) {}
};
// ✅ Rule of Five — when managing raw resources (rare)
class Buffer {
char* data_;
size_t size_;
public:
~Buffer(); // Destructor
Buffer(const Buffer&); // Copy constructor
Buffer& operator=(const Buffer&); // Copy assignment
Buffer(Buffer&&) noexcept; // Move constructor
Buffer& operator=(Buffer&&) noexcept; // Move assignment
};
Pass by value and move for sink parameters:
// ✅ Sink parameter — takes ownership
void addTask(Task task) {
tasks_.push_back(std::move(task));
}
// ✅ Read-only — const reference
void printTask(const Task& task);
// ❌ Never pass smart pointers unless transferring ownership
void processTask(std::shared_ptr<Task> task); // Unnecessary ref-count bump
// ✅ If function doesn't need ownership
void processTask(const Task& task);
Error Handling
For universal error handling principles, see .agents/rules/error-handling-principles.md. Below: language-specific patterns only.
std::expected (C++23) or Result types for expected failures:
// ✅ C++23 std::expected
std::expected<Task, TaskError> getTask(std::string_view id) {
auto it = tasks_.find(id);
if (it == tasks_.end()) {
return std::unexpected(TaskError::NotFound);
}
return it->second;
}
// Caller handles both paths
auto result = getTask("123");
if (!result) {
handleError(result.error());
return;
}
processTask(*result);
Exceptions for exceptional conditions only. Never for control flow.
noexcept on move constructors and destructors.
Domain error types:
enum class TaskError {
NotFound,
ValidationFailed,
StorageUnavailable,
};
// ✅ For exception-based paths
class TaskNotFoundException : public std::runtime_error {
std::string task_id_;
public:
explicit TaskNotFoundException(std::string id)
: std::runtime_error("Task not found: " + id), task_id_(std::move(id)) {}
const std::string& task_id() const noexcept { return task_id_; }
};
Modern Features
std::string_view for read-only string parameters (no allocation):
// ✅ Zero-copy string parameter
void log(std::string_view message, std::string_view context);
// ❌ Unnecessary copy
void log(const std::string& message);
constexpr for compile-time evaluation:
constexpr int maxRetries = 3;
constexpr auto timeout = std::chrono::seconds(30);
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
Structured bindings: auto [id, title] = getTask();
std::optional for nullable values:
// ✅ Explicit nullability
std::optional<Task> findById(std::string_view id);
// Caller checks explicitly
if (auto task = findById("123"); task.has_value()) {
process(*task);
}
std::variant for type-safe unions (sum types):
using TaskResult = std::variant<Task, TaskError>;
TaskResult result = getTask(id);
std::visit(overloaded{
[](const Task& task) { process(task); },
[](TaskError err) { handleError(err); },
}, result);
Concepts (C++20) for constrained templates:
template<typename T>
concept Storable = requires(T t) {
{ t.id() } -> std::convertible_to<std::string_view>;
{ t.serialize() } -> std::same_as<std::vector<char>>;
};
template<Storable T>
void save(const T& entity);
Ranges (C++20) for functional-style pipelines:
auto active_titles = tasks
| std::views::filter([](const Task& t) { return t.is_active(); })
| std::views::transform(&Task::title)
| std::views::take(10);
Interfaces and DI
// ✅ Interface (abstract class with pure virtuals)
class TaskStorage {
public:
virtual ~TaskStorage() = default;
virtual std::expected<Task, TaskError> getById(std::string_view id) = 0;
virtual void save(const Task& task) = 0;
};
// ✅ Production implementation
class PostgresTaskStorage : public TaskStorage {
// ...
};
// ✅ Test implementation
class MockTaskStorage : public TaskStorage {
// MOCK_METHOD from Google Mock, or hand-rolled
};
// ✅ Constructor injection
class TaskService {
std::unique_ptr<TaskStorage> storage_;
public:
explicit TaskService(std::unique_ptr<TaskStorage> storage)
: storage_(std::move(storage)) {}
};
Naming
- PascalCase for types. camelCase or snake_case for functions (project-consistent).
_ suffix for private members: storage_, logger_.
- No Hungarian notation.
- ALL_CAPS only for macros — never for constants (use
constexpr).
Anti-Patterns
Testing
Google Test or Catch2. Google Mock for interface mocking.
// Google Test + Google Mock
TEST(TaskServiceTest, ReturnsNotFoundForMissingTask) {
auto storage = std::make_unique<MockTaskStorage>();
EXPECT_CALL(*storage, getById("999"))
.WillOnce(Return(std::unexpected(TaskError::NotFound)));
TaskService service(std::move(storage));
auto result = service.getTask("999");
EXPECT_FALSE(result.has_value());
EXPECT_EQ(result.error(), TaskError::NotFound);
}
Formatting and Static Analysis
| Tool |
Purpose |
Command |
clang-format |
Formatting |
clang-format -i src/**/*.cpp |
clang-tidy |
Static analysis |
clang-tidy src/*.cpp -- |
cppcheck |
Bug detection |
cppcheck --enable=all src/ |
| AddressSanitizer |
Memory errors |
-fsanitize=address |
| ThreadSanitizer |
Race conditions |
-fsanitize=thread |
| UBSanitizer |
Undefined behavior |
-fsanitize=undefined |
Related
- Code Idioms and Conventions .agents/rules/code-idioms-and-conventions.md
- Resources and Memory Management @.agents/rules/resources-and-memory-management-principles.md
- Concurrency and Threading Principles @.agents/rules/concurrency-and-threading-principles.md
- Error Handling Principles @.agents/rules/error-handling-principles.md
1---2name: cpp-idioms-23description: C++ Idioms and Patterns4---56## C++ Idioms and Patterns78Modern C++ (17/20/23) rewards RAII, value semantics, and zero-cost abstractions. Lean into the type system and smart pointers. Idiomatic C++ = safe, deterministic, performant.910> Scope: C++ coding idioms. Test naming: .agents/rules/testing-strategy.md.1112### Ownership and Memory13141. **RAII — resources tied to object lifetime. No manual `new`/`delete`.**152. **`std::unique_ptr` for exclusive ownership, `std::shared_ptr` only when sharing is necessary.**163. **Move semantics — prefer moving over copying for expensive types.**174. **Rule of Five/Zero:**18 ```cpp19 // ✅ Rule of Zero — let compiler-generated defaults work20 class TaskService {21 std::unique_ptr<TaskStorage> storage_;22 std::shared_ptr<Logger> logger_;23 public:24 // No destructor, copy/move constructors needed — smart pointers handle it25 explicit TaskService(std::unique_ptr<TaskStorage> storage, std::shared_ptr<Logger> logger)26 : storage_(std::move(storage)), logger_(std::move(logger)) {}27 };2829 // ✅ Rule of Five — when managing raw resources (rare)30 class Buffer {31 char* data_;32 size_t size_;33 public:34 ~Buffer(); // Destructor35 Buffer(const Buffer&); // Copy constructor36 Buffer& operator=(const Buffer&); // Copy assignment37 Buffer(Buffer&&) noexcept; // Move constructor38 Buffer& operator=(Buffer&&) noexcept; // Move assignment39 };40 ```41425. **Pass by value and move for sink parameters:**43 ```cpp44 // ✅ Sink parameter — takes ownership45 void addTask(Task task) {46 tasks_.push_back(std::move(task));47 }4849 // ✅ Read-only — const reference50 void printTask(const Task& task);5152 // ❌ Never pass smart pointers unless transferring ownership53 void processTask(std::shared_ptr<Task> task); // Unnecessary ref-count bump5455 // ✅ If function doesn't need ownership56 void processTask(const Task& task);57 ```5859### Error Handling6061> For universal error handling principles, see `.agents/rules/error-handling-principles.md`. Below: language-specific patterns only.62631. **`std::expected` (C++23) or Result types for expected failures:**64 ```cpp65 // ✅ C++23 std::expected66 std::expected<Task, TaskError> getTask(std::string_view id) {67 auto it = tasks_.find(id);68 if (it == tasks_.end()) {69 return std::unexpected(TaskError::NotFound);70 }71 return it->second;72 }7374 // Caller handles both paths75 auto result = getTask("123");76 if (!result) {77 handleError(result.error());78 return;79 }80 processTask(*result);81 ```82832. **Exceptions for exceptional conditions only.** Never for control flow.843. **`noexcept` on move constructors and destructors.**854. **Domain error types:**86 ```cpp87 enum class TaskError {88 NotFound,89 ValidationFailed,90 StorageUnavailable,91 };9293 // ✅ For exception-based paths94 class TaskNotFoundException : public std::runtime_error {95 std::string task_id_;96 public:97 explicit TaskNotFoundException(std::string id)98 : std::runtime_error("Task not found: " + id), task_id_(std::move(id)) {}99 const std::string& task_id() const noexcept { return task_id_; }100 };101 ```102103### Modern Features1041051. **`std::string_view`** for read-only string parameters (no allocation):106 ```cpp107 // ✅ Zero-copy string parameter108 void log(std::string_view message, std::string_view context);109110 // ❌ Unnecessary copy111 void log(const std::string& message);112 ```1131142. **`constexpr`** for compile-time evaluation:115 ```cpp116 constexpr int maxRetries = 3;117 constexpr auto timeout = std::chrono::seconds(30);118119 constexpr int factorial(int n) {120 return n <= 1 ? 1 : n * factorial(n - 1);121 }122 ```1231243. **Structured bindings**: `auto [id, title] = getTask();`1254. **`std::optional`** for nullable values:126 ```cpp127 // ✅ Explicit nullability128 std::optional<Task> findById(std::string_view id);129130 // Caller checks explicitly131 if (auto task = findById("123"); task.has_value()) {132 process(*task);133 }134 ```1351365. **`std::variant`** for type-safe unions (sum types):137 ```cpp138 using TaskResult = std::variant<Task, TaskError>;139140 TaskResult result = getTask(id);141 std::visit(overloaded{142 [](const Task& task) { process(task); },143 [](TaskError err) { handleError(err); },144 }, result);145 ```1461476. **Concepts (C++20)** for constrained templates:148 ```cpp149 template<typename T>150 concept Storable = requires(T t) {151 { t.id() } -> std::convertible_to<std::string_view>;152 { t.serialize() } -> std::same_as<std::vector<char>>;153 };154155 template<Storable T>156 void save(const T& entity);157 ```1581597. **Ranges (C++20)** for functional-style pipelines:160 ```cpp161 auto active_titles = tasks162 | std::views::filter([](const Task& t) { return t.is_active(); })163 | std::views::transform(&Task::title)164 | std::views::take(10);165 ```166167### Interfaces and DI168169```cpp170// ✅ Interface (abstract class with pure virtuals)171class TaskStorage {172public:173 virtual ~TaskStorage() = default;174 virtual std::expected<Task, TaskError> getById(std::string_view id) = 0;175 virtual void save(const Task& task) = 0;176};177178// ✅ Production implementation179class PostgresTaskStorage : public TaskStorage {180 // ...181};182183// ✅ Test implementation184class MockTaskStorage : public TaskStorage {185 // MOCK_METHOD from Google Mock, or hand-rolled186};187188// ✅ Constructor injection189class TaskService {190 std::unique_ptr<TaskStorage> storage_;191public:192 explicit TaskService(std::unique_ptr<TaskStorage> storage)193 : storage_(std::move(storage)) {}194};195```196197### Naming1981991. **PascalCase** for types. **camelCase** or **snake_case** for functions (project-consistent).2002. **`_` suffix** for private members: `storage_`, `logger_`.2013. No Hungarian notation.2024. **ALL_CAPS** only for macros — never for constants (use `constexpr`).203204### Anti-Patterns205206- ❌ **Raw `new`/`delete`** — use `std::make_unique` / `std::make_shared`207- ❌ **`using namespace std;`** in headers — pollutes global namespace208- ❌ **Catching `...` without re-throwing** — swallows all errors including crashes209- ❌ **`const_cast` to remove constness** — design flaw, fix the interface210- ❌ **`reinterpret_cast` without safety justification** — undefined behavior risk211- ❌ **C-style casts `(int)x`** — use `static_cast<int>(x)` for type safety212- ❌ **`std::shared_ptr` when `std::unique_ptr` suffices** — unnecessary overhead213- ❌ **Copy-heavy loops without `const auto&`:**214 ```cpp215 // ❌ Copies every Task216 for (auto task : tasks) { process(task); }217218 // ✅ Reference — no copy219 for (const auto& task : tasks) { process(task); }220 ```221222### Testing223224Google Test or Catch2. Google Mock for interface mocking.225226```cpp227// Google Test + Google Mock228TEST(TaskServiceTest, ReturnsNotFoundForMissingTask) {229 auto storage = std::make_unique<MockTaskStorage>();230 EXPECT_CALL(*storage, getById("999"))231 .WillOnce(Return(std::unexpected(TaskError::NotFound)));232233 TaskService service(std::move(storage));234 auto result = service.getTask("999");235236 EXPECT_FALSE(result.has_value());237 EXPECT_EQ(result.error(), TaskError::NotFound);238}239```240241### Formatting and Static Analysis242243| Tool | Purpose | Command |244|---|---|---|245| `clang-format` | Formatting | `clang-format -i src/**/*.cpp` |246| `clang-tidy` | Static analysis | `clang-tidy src/*.cpp --` |247| `cppcheck` | Bug detection | `cppcheck --enable=all src/` |248| AddressSanitizer | Memory errors | `-fsanitize=address` |249| ThreadSanitizer | Race conditions | `-fsanitize=thread` |250| UBSanitizer | Undefined behavior | `-fsanitize=undefined` |251252### Related253- Code Idioms and Conventions .agents/rules/code-idioms-and-conventions.md254- Resources and Memory Management @.agents/rules/resources-and-memory-management-principles.md255- Concurrency and Threading Principles @.agents/rules/concurrency-and-threading-principles.md256- Error Handling Principles @.agents/rules/error-handling-principles.md