Leo*_*eon 4 c++ lazy-evaluation auto c++11
这个问题与现有问题“使用 C++11 的‘自动’能否提高性能? ”相反。
该问题的一个答案表明,使用auto
不仅会产生积极的影响,还会产生消极的影响。
我相信我们需要一个单独的问题,答案集中在auto
.
随着auto
有在变量声明+初始行任何转换。但是如果这种转换无论如何都必须发生,最好在初始化期间发生一次而不是多次发生。
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
Run Code Online (Sandbox Code Playgroud)
当auto
与惰性求值(真实世界示例 1,示例 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'
Run Code Online (Sandbox Code Playgroud)