[Development] RFC: more liberal 'auto' rules?

Marc Mutz marc.mutz at kdab.com
Thu Dec 3 19:49:46 CET 2015


The wiki[1] currently contains some rules for how to use automatic type 
deduction for variables (Q_C_AUTO_TYPE) that are very restrictive.

[1] I get an ERROR: state not found when trying to log in, btw.

And pointless.

The remainder of the C++ world is moving towards an "always auto" scheme. We 
don't need to go there, but I'd at least like to propose, for new code and as 
a drive-by, the *required* use of auto for:

- template code (esp., but not necessarily only, when the type name would
  require the use of 'typename')
- all loop variables (both index and iterators)
  the reason being that spelling out the name is usually wrong:
  size_t i = stdVector.size() // wrong, should be std::vector::size_type...
  also helps when porting from Qt containers to STL ones
- all references to elements in a collection (same problem - way too easy to
  misspell std::pair<int, int> for std::pair<const int, int>...)

Optional use of auto: whereever it makes sense. Use your own judgement, but 
remember: fear is a bad advisor.

For range-for, I'd suggest the following patterns:

- loop variable: singular name of collection name (foo : foos)
  - otherwise: 'e' (for element) or first letter (r : rects)
- for (auto e : collection) // (for pass-by-value types, or if you modify)
- for (const auto &e : collection) // for pass-by-reference types
- for (auto &e : collection) // mutating (also: pointer variables/no auto *&e)
- for (const auto *e : collection) // const pointers
- for (auto *e : collection) // non-const pointer
- explicit type name should be the exception

This is covering a large part of the usefulness of auto.

I don't really like to add anything more detailed to the "rules". Scott 
Meyers' books do a much better job at explaining than we ever could.



Marc Mutz <marc.mutz at kdab.com> | Senior Software Engineer
KDAB (Deutschland) GmbH & Co.KG, a KDAB Group Company
Tel: +49-30-521325470
KDAB - The Qt Experts

More information about the Development mailing list