Is there a downside to declaring variables with auto in C++?

后端 未结 14 2056
-上瘾入骨i
-上瘾入骨i 2020-12-12 18:14

It seems that auto was a fairly significant feature to be added in C++11 that seems to follow a lot of the newer languages. As with a language like Python, I ha

14条回答
  •  时光取名叫无心
    2020-12-12 18:59

    Keyword auto simply deduce the type from the return value. Therefore, it is not equivalent with a Python object, e.g.

    # Python
    a
    a = 10       # OK
    a = "10"     # OK
    a = ClassA() # OK
    
    // C++
    auto a;      // Unable to deduce variable a
    auto a = 10; // OK
    a = "10";    // Value of const char* can't be assigned to int
    a = ClassA{} // Value of ClassA can't be assigned to int
    a = 10.0;    // OK, implicit casting warning
    

    Since auto is deduced during compilation, it won't have any drawback at runtime whatsoever.

提交回复
热议问题