From 3216d29e5181c361fca68a6158d5a18eb46a08b7 Mon Sep 17 00:00:00 2001 From: Pieter Hijma Date: Fri, 4 Apr 2025 13:48:11 +0200 Subject: [PATCH 1/2] Fix a small bug in the heading levels --- bestpractices/c++practices.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bestpractices/c++practices.md b/bestpractices/c++practices.md index 27d8eeb..38a57d9 100644 --- a/bestpractices/c++practices.md +++ b/bestpractices/c++practices.md @@ -445,7 +445,7 @@ constexpr auto redDogColor {"red"}; // OK ``` See also variable sets. -# Out parameters +## Out parameters Out parameters are _non-const, by-reference, or by-pointer_, function parameters. These are known to cause hard to find bugs. From 389bfcc21b0db82e0f19a2988975bad81b062ff4 Mon Sep 17 00:00:00 2001 From: Pieter Hijma Date: Fri, 4 Apr 2025 14:14:49 +0200 Subject: [PATCH 2/2] Add guidelines for typeing c++ with auto --- bestpractices/c++practices.md | 52 +++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/bestpractices/c++practices.md b/bestpractices/c++practices.md index 38a57d9..f7f5c48 100644 --- a/bestpractices/c++practices.md +++ b/bestpractices/c++practices.md @@ -247,6 +247,58 @@ A well-designed class manages its own state and provides behavior, not just acce Using strings for everything can make code harder to understand and maintain. Use appropriate types to add clarity and structure. +### The use of `auto` + +The use of `auto` has not yet been discussed in the C++ Core Guidelines (see +[the to-do +list](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#to-do-unclassified-proto-rules)). +Below follow general guidelines with examples: + +#### The use of `auto` is ok if the right-hand side makes clear which type it is + +```c++ +auto* xyz = new Xyz(); +``` + +```c++ +auto xyz = _cast(...); +``` + +```c++ +auto xyz = getAnything(...); +``` + +Counter examples: + +```c++ +auto value = randomThing.weirdProperty->getValue(); // non-obvious type +``` + +```c++ +auto doStuff() { ... } // auto as return type +``` + +```c++ +auto xyz = 1; // unclear what type of integer +``` + +#### The use of `auto` is ok if the type is long or verbose + +```c++ +auto it = foo.begin(); // iterator +``` + +```c++ +auto lambda = [](){...}; +``` + +#### The use of `auto` is ok if redundancy is avoided + +```c++ +std::unordered_map map; +for (const auto& [key, value] : map) { ... } +``` + ## Main code path and indentation > If you are past three indents you are basically screwed.