这个问题与现有问题“Can the use of C++11's 'auto' improve performance?”相反
One of the answers这个问题表明使用 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
当 auto
与惰性求值(真实世界 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'
关于c++ - 使用 C++1 1's ' auto' 会降低性能甚至破坏代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38415831/