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

Ziller Eike Eike.Ziller at theqtcompany.com
Tue Dec 22 11:26:40 CET 2015

> On Dec 8, 2015, at 10:46 AM, Ziller Eike <Eike.Ziller at theqtcompany.com> wrote:
>> On Dec 7, 2015, at 2:41 PM, Knoll Lars <Lars.Knoll at theqtcompany.com> wrote:
>> On 07/12/15 15:44, "Development on behalf of Marc Mutz" <development-bounces at qt-project.org on behalf of marc.mutz at kdab.com> wrote:
>>> On Monday 07 December 2015 13:48:58 Ziller Eike wrote:
>>>> I do not think that more usage of ‘auto’ will make any code (or
>>>> refactorings of it) ‘safer’. IMO this is only about convenience and
>>>> readability.
>>> std::map<std::string, std::string> stdMap = ...;
>>> for (const std::pair<std::string, std::string> &e : stdMap)
>>>    doSomething(e.first, e.second);
>>> for (const auto &e : stdMap)
>>>    doSomething(e.first, e.second);
>>> The second loop is at least two orders of magnitude faster (doSomething() is 
>>> an out-of-line no-op).
>> I think the summary here is that auto gives you one guarantee: It won’t do an implicit conversion for the initial assignment.

So, directly after the above example in Item 5, Item 6 in Effective Modern C++ continues with the examples of how you can shoot yourself in the foot _because_ you used auto.

std::vector<bool> features(const MyType &w);
MyType w;
auto someFeatureActive = features(w)[5];
doSomething(someFeatureActive); // <---- undefined behavior because someFeatureActive is _not_ a bool

We have something similar in Qt:

    QString a = "ABC";
    QString b = "abc";
    auto result = a + b;
    a.replace("A", "C");
    qDebug() << result;

prints “CBCabc” instead of “ABCabc” when QT_USE_FAST_OPERATOR_PLUS is defined, because result is not a QString in that case.

So funny/unwanted behavior can occur both because one used the wrong explicit type, and because one used auto instead of an explicit type.

> Granted.
> I really wonder though, why it is possible to assign the wrong type to a _reference_ here, even if it is const ?
> I cannot do that with e.g. a std::vector (std::vector<const std::string> v; const std::vector<std::string> &v2 = v;), so is that some funny thing with std::pair?
> The spirit of the “you can use auto when assigning iterator type” was to mean “you can use auto when assigning long ugly template types” at least in case of ‘known patterns' (of which we do not have too many in Qt API, therefore iterator types). So I think this use of auto is covered by the “spirit” of the rule.
> Br, Eike

Eike Ziller, Senior Software Engineer - The Qt Company GmbH
The Qt Company GmbH, Rudower Chaussee 13, D-12489 Berlin
Geschäftsführer: Mika Pälsi, Juha Varelius, Tuula Haataja
Sitz der Gesellschaft: Berlin, Registergericht: Amtsgericht Charlottenburg, HRB 144331 B

More information about the Development mailing list