Skip to content

Add guidelines for use of auto for types in C++ #123

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 4, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion bestpractices/c++practices.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <whatever>_cast<Xyz>(...);
```

```c++
auto xyz = getAnything<Xyz>(...);
```

Counter examples:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure everyone knows what "counter" examples mean.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, can you review #129?


```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<std::string, int> map;
for (const auto& [key, value] : map) { ... }
```

## Main code path and indentation

> If you are past three indents you are basically screwed.
Expand Down Expand Up @@ -445,7 +497,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.

Expand Down