DEV Community

David Sporn
David Sporn

Posted on

C++ development notes : about `auto`

It's been almost six monthes since I started a new C++ project with the intent of refreshing my practices for this language. Before that attempt, I stuck to a kind of "C with classes" style of programming, as it was enough to get things done (essentially, some little projects on micro-controllers).

Now I use the stl, like vectors, map, optional, expected, unique_ptr, etc...

But one feature that I want to avoid as much as possible is the auto keyword. I wrote a programming rule for myself named auto is evil.

That rule states that auto is generally banned, with one exception.

My rationale is the following :

  • Primary rationale : the keyword auto hides knowledge. It's bad for discovering a foreign codebase, as well as for learning the language. How could I learn about what type is that iterators if everyone write auto instead of some_template<args>::iterator or some_template<args>::const_iterator ?
  • Secondary rationale : while searching about advantages and drawbacks of auto, I discovered that it may trigger unwanted copy or move, as explained there : https://medium.com/@rogerbooth/c-gotcha-unnecessary-copies-due-to-the-misuse-of-auto-ed24e65b5efd).

Now, there is only one exception, where auto seems unavoidable : declaring a lambda, e.g. auto myHandler = [/*capture list*/](/*args list*/)->someType{/*body*/} ;.

However, I would challenge the use of auto in favor of, say std::function, UNLESS there is a strong motivation in favor of auto because of a critical performance problem.

And one day, I MAY look into cdecltype(...) and templates to try to designate some usual pattern like Java's function package, in order to reduce even more the use of auto.

Speaking about Java, by the way, I also ban the var keyword that is the Java equivalent of auto, for the same primary rationale

Top comments (0)