Skip to content

Commit e791abe

Browse files
addaleaxtargos
authored andcommitted
doc: formalize auto usage in C++ style guide
We generally avoid using `auto` if not necessary. This formalizes this rules by writing them down in the C++ style guide. PR-URL: #23028 Reviewed-By: Tobias Nießen <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Refael Ackermann <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: Gireesh Punathil <[email protected]> Reviewed-By: Daniel Bevenius <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: Michael Dawson <[email protected]>
1 parent cb0d823 commit e791abe

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

CPP_STYLE_GUIDE.md

+19
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
* [Ownership and Smart Pointers](#ownership-and-smart-pointers)
2121
* [Others](#others)
2222
* [Type casting](#type-casting)
23+
* [Using `auto`](#using-auto)
2324
* [Do not include `*.h` if `*-inl.h` has already been included](#do-not-include-h-if--inlh-has-already-been-included)
2425
* [Avoid throwing JavaScript errors in C++ methods](#avoid-throwing-javascript-errors-in-c)
2526
* [Avoid throwing JavaScript errors in nested C++ methods](#avoid-throwing-javascript-errors-in-nested-c-methods)
@@ -209,6 +210,24 @@ Never use `std::auto_ptr`. Instead, use `std::unique_ptr`.
209210
- Use `static_cast` for casting whenever it works
210211
- `reinterpret_cast` is okay if `static_cast` is not appropriate
211212
213+
### Using `auto`
214+
215+
Being explicit about types is usually preferred over using `auto`.
216+
217+
Use `auto` to avoid type names that are noisy, obvious, or unimportant. When
218+
doing so, keep in mind that explicit types often help with readability and
219+
verifying the correctness of code.
220+
221+
```cpp
222+
for (const auto& item : some_map) {
223+
const KeyType& key = item.first;
224+
const ValType& value = item.second;
225+
// The rest of the loop can now just refer to key and value,
226+
// a reader can see the types in question, and we've avoided
227+
// the too-common case of extra copies in this iteration.
228+
}
229+
```
230+
212231
### Do not include `*.h` if `*-inl.h` has already been included
213232

214233
Do

0 commit comments

Comments
 (0)