Skip to content

Commit c7db7ce

Browse files
pieterhijmachennes
authored andcommitted
Add guidelines for typeing c++ with auto
1 parent bc089a0 commit c7db7ce

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

bestpractices/c++practices.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,58 @@ A well-designed class manages its own state and provides behavior, not just acce
247247

248248
Using strings for everything can make code harder to understand and maintain. Use appropriate types to add clarity and structure.
249249

250+
### The use of `auto`
251+
252+
The use of `auto` has not yet been discussed in the C++ Core Guidelines (see
253+
[the to-do
254+
list](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#to-do-unclassified-proto-rules)).
255+
Below follow general guidelines with examples:
256+
257+
#### The use of `auto` is ok if the right-hand side makes clear which type it is
258+
259+
```c++
260+
auto* xyz = new Xyz();
261+
```
262+
263+
```c++
264+
auto xyz = <whatever>_cast<Xyz>(...);
265+
```
266+
267+
```c++
268+
auto xyz = getAnything<Xyz>(...);
269+
```
270+
271+
Counter examples:
272+
273+
```c++
274+
auto value = randomThing.weirdProperty->getValue(); // non-obvious type
275+
```
276+
277+
```c++
278+
auto doStuff() { ... } // auto as return type
279+
```
280+
281+
```c++
282+
auto xyz = 1; // unclear what type of integer
283+
```
284+
285+
#### The use of `auto` is ok if the type is long or verbose
286+
287+
```c++
288+
auto it = foo.begin(); // iterator
289+
```
290+
291+
```c++
292+
auto lambda = [](){...};
293+
```
294+
295+
#### The use of `auto` is ok if redundancy is avoided
296+
297+
```c++
298+
std::unordered_map<std::string, int> map;
299+
for (const auto& [key, value] : map) { ... }
300+
```
301+
250302
## Main code path and indentation
251303

252304
> If you are past three indents you are basically screwed.

0 commit comments

Comments
 (0)