可以使用C ++ 11的'auto'提高性能吗? [英] Can the use of C++11's 'auto' improve performance?

查看:163
本文介绍了可以使用C ++ 11的'auto'提高性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以看到为什么C ++ 11中的 auto 类型提高了正确性和可维护性。我已经读过,它也可以提高性能(几乎总是

I can see why the auto type in C++11 improves correctness and maintainability. I've read that it can also improve performance (Almost Always Auto by Herb Sutter), but I miss a good explanation.


  • 如何自动
  • How can auto improve performance?
  • Can anyone give an example?

推荐答案

auto 可以通过避免静默隐式转换来提高性能。我发现一个令人信服的例子如下。

auto can aid performance by avoiding silent implicit conversions. An example I find compelling is the following.

std::map<Key, Val> m;
// ...

for (std::pair<Key, Val> const& item : m) {
    // do stuff
}

看到错误?在这里,我们认为我们通过const引用优化地图中的每个项目,并使用新的范围 - 表达式使我们的意图清楚,但实际上我们复制个元素。这是因为 std :: map< Key,Val> :: value_type std :: pair< const Key,Val> ,而不是 std :: pair< Key,Val> 。因此,当我们(隐含地)具有:

See the bug? Here we are, thinking we're elegantly taking every item in the map by const reference and using the new range-for expression to make our intent clear, but actually we're copying every element. This is because std::map<Key, Val>::value_type is std::pair<const Key, Val>, not std::pair<Key, Val>. Thus, when we (implicitly) have:

std::pair<Key, Val> const& item = *iter;

而不是引用一个现有的对象并保留它,我们必须做一个类型转换。只要存在隐式转换,例如:

Instead of taking a reference to an existing object and leaving it at that, we have to do a type conversion. You are allowed to take a const reference to an object (or temporary) of a different type as long as there is an implicit conversion available, e.g.:

int const& i = 2.0; // perfectly OK

类型转换是允许的隐式转换,因为同样的原因, code> const Key ,但是我们必须构造一个新类型的临时,以允许。因此,我们的循环有效:

The type conversion is an allowed implicit conversion for the same reason you can convert a const Key to a Key, but we have to construct a temporary of the new type in order to allow for that. Thus, effectively our loop does:

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 对象,它只是为了说明,实际上未命名的临时只是绑定到为其生命周期)。

(Of course, there isn't actually a __tmp object, it's just there for illustration, in reality the unnamed temporary is just bound to item for its lifetime).

只要更改为:

for (auto const& item : m) {
    // do stuff
}

of copies - 现在引用的类型与初始化器类型匹配,因此不需要临时或转换,我们可以直接引用。

just saved us a ton of copies - now the referenced type matches the initializer type, so no temporary or conversion is necessary, we can just do a direct reference.

这篇关于可以使用C ++ 11的'auto'提高性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆