我明白为什么 C++11 中的 auto
类型会提高正确性和可维护性。我读过它还可以提高性能(Almost Always Auto 由 Herb Sutter 撰写),但我错过了一个很好的解释。
auto
如何提高性能?- 谁能举个例子?
最佳答案
auto
可以通过避免静默隐式转换来提高性能。我觉得引人注目的一个例子如下。
std::map<Key, Val> m;
// ...
for (std::pair<Key, Val> const& item : m) {
// do stuff
}
看到错误了吗?在这里,我们认为我们通过 const 引用优雅地获取 map 中的每个项目并使用新的 range-for 表达式来明确我们的意图,但实际上我们正在复制 每个 元素。这是因为 std::map<Key, Val>::value_type
是 std::pair<const Key, Val>
,而不是 std::pair<Key, Val>
.因此,当我们(隐含地)有:
std::pair<Key, Val> const& item = *iter;
我们必须进行类型转换,而不是获取对现有对象的引用并将其保留在那里。只要有可用的隐式转换,您就可以对不同类型的对象(或临时对象)进行 const 引用,例如:
int const& i = 2.0; // perfectly OK
类型转换是允许的隐式转换,原因与您可以转换 const Key
的原因相同。到 Key
,但我们必须构造一个新类型的临时变量以允许这样做。因此,我们的循环实际上是:
std::pair<Key, Val> __tmp = *iter; // construct a temporary of the correct type
std::pair<Key, Val> const& item = __tmp; // then, take a reference to it
(当然,实际上并没有 __tmp
对象,它只是为了说明而存在,实际上未命名的临时对象在其生命周期内只是绑定(bind)到 item
)。
只是改成:
for (auto const& item : m) {
// do stuff
}
刚刚为我们节省了大量拷贝 - 现在引用的类型与初始化器类型匹配,因此不需要临时或转换,我们可以直接引用。
关于c++ - 使用 C++1 1's ' auto' 可以提高性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32510183/