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

André Pönitz apoenitz at t-online.de
Fri Dec 4 21:35:16 CET 2015

On Fri, Dec 04, 2015 at 08:01:59PM +0100, Olivier Goffart wrote:
> > > You don't see any type.
> > > 
> > > This code that use auto is not less readable. Even if you don't know
> > > what's the type of bar without looking it up.
> > > 
> > >   auto *bar = foo->bar();
> > >   bar->setFaz(m_factory->createFaz(bar->type()));
> > 
> > Isn't this kind of a bad example, because there was no type declared/visible
> > in the first place?
> Precisely my point!   
> There is no type visible before and nobody complains.  So why should one 
> suddenly complains there are no types in the second snippet

Because they are different from a human reader's point of view.

In the second snippet the scope of the 'bar' is larger than for an immediate
use. This loses the context in which it is used, i.e. makes it harder to
reason about whether the use is ok, and adds load on a human reader that
needs to keep mental track of this 'untyped' item when reading the code until
it goes out of scope in case there's another use of this item.

Both alternatives help to reduce that load:

- immediate consumption of the temporary makes it explicit that the item is
  used exactly once and provides the consumer as additional context, helping
  judging whether the use is ok,

- using a separate line with a real type provides a stepping stone by
  giving additional information about the intermediate item *to the
  human reader*, helping him to split the task of verifying that
  'the right thing is produced and consumed' into smaller subtasks.

> > I really dislike hiding types behind a generic keyword.
> Because the type is redundent

It might be redundant for the compiler, but it is not for human
readers of the code.

> and it's one reason less to make errors:
> Using 'int' instead of 'quint64' or 'size_t', or QString instead of QByteArray 
> is way to frequent. (and the compiler won't complain)

["QString instead of QByteArray" does not happen with proper
QT_NO__CAST_*_ASCII settings.  Not to mention the cases where mindless
replacement of explicit types by 'auto' doesn't produce identical results.]

> It is also refactoring-proof.  Because you might want to change the name of
> the type from "FazManager" to "FazHolder", and then you need to touch less
> code in your refactoring

Code is typically read more often than changed. Targeting at making
specific refactorings easier is optimizing the wrong utility function.


More information about the Development mailing list