c++ - 使用 C++1 1's ' auto' 会降低性能甚至破坏代码吗?

标签 c++ c++11 lazy-evaluation auto

这个问题与现有问题“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/

相关文章:

c++ - 打开保存文件对话框时进程崩溃并显示消息 "RPC server is unavailable"?

c++ - 有没有办法让 C++ Switch 语句循环回到第一种情况?

c++ - 为什么 "unsigned int ui = {-1};"是缩小转换错误?

.net - Directory.EnumerateFiles => UnauthorizedAccessException

ios - iOS 延迟初始化

c++ - 如何在 Qt 中为每个工具栏部分提供标题

c++ - 在 C++ 中返回此指针的函数

c++ - 为什么将 std::string 传递给 CString.Format() 有时只会崩溃?

c++ - 模板类不同的返回类型取决于类参数

haskell - "circular list"中相邻元素对的延迟生成