[Qt-creator] Using C++11 in Creator's source
Jonathan S. Shapiro
shap at eros-os.org
Wed Mar 5 21:20:13 CET 2014
Folks:
I have a lot of experience with type inference in other languages and some
with auto in C++11. It's hard to decide what idioms are comfortable until
you have some familiarity with the practice. It's also important to
remember that what C++11 does *isn't* type inference. The distinction is
sometimes confusing.
In my experience in C++11, the overwhelmingly useful motivation for auto is
iterators and other collection type names (value_type, key_type,
mapped_type, and so forth). The sheer length of the identifiers for those
types is brutal. Using auto in for(;;) and foreach is particularly useful,
as it *dramatically* lowers both the typographic overhead and the
likelihood of mistakes.
Somebody suggested avoiding things like:
auto i = 5;
I agree. Partly because you won't get the type you thought you wanted. :-)
Somebody else put forward:
auto *p = new SomethingOrOther()
I'd say no. For that, you probably want:
auto p = new SomethingOrOther()
That is: let auto do it's job if you are going to use it.
For those who like the documentation that explicit types provide, I think
that's a judgment call. More than anything, it's a matter of what's
familiar, and that will change over time. It also depends on whether you
adopt the hungarian-style variable name conventions or not. I personally
hate the hungarian naming conventions, but other people like it, and their
reasons don't strike me as crazy.
One thing to keep in mind is that variables declared "auto" will track
changes. If the type of NewMenu() changes at some point, then
auto myMenu = NewMenu()
requires no change, but
QMenu myMenu = NewMenu()
will have to be updated.
Because auto actually isn't type inference, it turns out to be less useful
for local declarations than it might initially appear.
Personally, I think that type names as documentation for locals have
limited value. If you don't know what NewMenu() returns, you shouldn't be
calling it in any case. Dropping the explicit types has a significant
advantage when new code is being written, because it reduces the amount of
type name changes you are forced to make. All of this is especially true
for temporary variables that go out of use after only a few lines.
I have no general conclusions or even recommendations - this is something
where the community needs to decide on a working fit. What I *do* suggest
is that some experimenting is in order to see what feels natural after a
bit of experience.
Jonathan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/qt-creator/attachments/20140305/8a18bfb1/attachment.html>
More information about the Qt-creator
mailing list