auto and expression templates

suggest change

auto can also cause problems where expression templates come into play:

auto mult(int c) {
    return c * std::valarray<int>{1};
}

auto v = mult(3);
std::cout << v[0]; // 3 if operator* returns std::valarray<int>

With libraries where this operator* returns std::valarray<int> by value (such as Microsoft's STL), v[0] is 3. However, the standard permits it to return a different type, and some libraries (such as GCC's libstdc++) return an expression-template proxy that refers to the temporary valarray. auto would deduce that proxy, which dangles after the return, and reading v[0] would be undefined. Giving mult the explicit return type std::valarray<int> converts the proxy before that temporary is destroyed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents