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

后端 未结 14 2024
-上瘾入骨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:52

    I think auto is good when used in a localized context, where the reader easily & obviously can deduct its type, or well documented with a comment of its type or a name that infer the actual type. Those who don't understand how it works might take it in the wrong ways, like using it instead of template or similar. Here are some good and bad use cases in my opinion.

    void test (const int & a)
    {
        // b is not const
        // b is not a reference
    
        auto b = a;
    
        // b type is decided by the compiler based on value of a
        // a is int
    }
    

    Good Uses

    Iterators

    std::vector<boost::tuple<ClassWithLongName1,std::vector<ClassWithLongName2>,int> v();
    
    ..
    
    std::vector<boost::tuple<ClassWithLongName1,std::vector<ClassWithLongName2>,int>::iterator it = v.begin();
    
    // VS
    
    auto vi = v.begin();
    

    Function Pointers

    int test (ClassWithLongName1 a, ClassWithLongName2 b, int c)
    {
        ..
    }
    
    ..
    
    int (*fp)(ClassWithLongName1, ClassWithLongName2, int) = test;
    
    // VS
    
    auto *f = test;
    

    Bad Uses

    Data Flow

    auto input = "";
    
    ..
    
    auto output = test(input);
    

    Function Signature

    auto test (auto a, auto b, auto c)
    {
        ..
    }
    

    Trivial Cases

    for(auto i = 0; i < 100; i++)
    {
        ..
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题