On 6/2/2015 2:58 PM, smaug wrote:
Hi all,
there was some discussion in #developers about use of 'auto' earlier
today.
Some people seem to like it, and some, like I, don't.
The reasons why I try to avoid using it and usually ask to replace it
with the actual type when I'm
reviewing a patch using it are:
- It makes the code harder to read
* one needs to explicitly check what kind of type is assigned to the
variable
to see how the variable is supposed to be used. Very important for
example
when dealing with refcounted objects, and even more important when
dealing with raw pointers.
- It makes the code possibly error prone if the type is later changed.
* Say, you have a method nsRefPtr<Foo> Foo(); (I know, silly
example, but you get the point)
Now auto foo = Foo(); makes sure foo is kept alive.
But then someone decides to change the return value to Foo*.
Everything still compiles just fine, but use of foo becomes risky
and may lead to UAF.
There are a few use cases for auto, in rough order that their utility is
most evident:
* auto x = []() {}; Lambdas don't even have a name that you can write down.
* STL iterator names, e.g., auto it = map.find(stuff); The type name is
simultaneously obvious and obnoxious.
* auto x = static_cast<Foo*>(bar); You typed the name once, why should
you have to type it again.
* for (auto & x : vec).
The case which I am personally very much on the fence is integral types.
On the one hand, sometimes the type just doesn't matter and you want to
make sure that you have the same type. On the other hand, I have been
very burned before by getting the signedness wrong and having code blow up.
I think that the first three cases are cases where auto not only should
be permitted but be required by the style guide; otherwise, I think auto
should be permitted (to reviewer/module owner's taste) but generally
strongly advised against. In particular, use of auto in lieu of things
like T* or nsRefPtr<T> should be forbidden except in special
circumstances (automatically-generated code being an example), where its
use would be carefully checked for correctness.
Just my opinion :-)
--
Joshua Cranmer
Thunderbird and DXR developer
Source code archæologist
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform