Search code examples
c++c++11lazy-evaluationauto

Can the use of C++11's 'auto' deteriorate performance or even break the code?


This question is the opposite of an existing question "Can the use of C++11's 'auto' improve performance?"

One of the answers to that question indicated that usage of auto can have not only positive but also negative effects.

I believe we need a separate question, with answers focusing on that side of auto.


Solution

  • With auto there is no conversion at the variable declaration+initialization line. But if such conversion must happen anyway, it better happen once during initialization than multiple times later.

    struct X {
        ...
    };
    
    struct Y {
        operator X() const;
        ...
    };
    
    Y foo(); // maybe, originally its return type was X but later was changed to Y
    void bar(const X& );
    
    const auto x = foo();           // <-- conversion not happening here
                                    //
    for ( int i = 0; i < 100; ++i ) //
        bar(x);                     // <-- silently rages here
    

    Such a deferred conversion may break the code when auto is combined with lazy evaluation (real world example 1, example 2):

    class Matrix { ... };
    
    class MatrixExpression {
        ...
        operator Matrix() const;
    };
    
    MatrixExpression operator+(const Matrix& a, const Matrix& b);
    std::ostream& operator(std::ostream& out, const Matrix& m);
    
    Matrix a = ...;
    Matrix b = ...;
    auto c = a + b; // evaluation of the matrix addition doesn't happen here
    a[0][0] += 1;
    std::cout << c; // matrix addition is evaluated here, using the new state of 'a'