本文介绍了在基于范围的for循环中使用转发引用有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const auto&就足够了.但是,我碰到了

const auto& would suffice if I want to perform read-only operations. However, I have bumped into

for (auto&& e : v)  // v is non-const

最近几次.这让我感到奇怪:

a couple of times recently. This makes me wonder:

auto&const auto&相比,在某些晦涩的角落情况下使用转发引用是否有一些性能上的好处?

Is it possible that in some obscure corner cases there is some performance benefit in using forwarding references, compared to auto& or const auto&?

(shared_ptr是疑似死角案件)

更新我在收藏夹中找到了两个示例:

UpdateTwo examples that I found in my favorites:

在遍历基本类型时使用const引用有什么缺点吗?
我可以使用基于范围的for循环轻松地迭代地图的值吗?

请关注以下问题:我为什么要使用自动&&在基于范围的for循环中?

推荐答案

我唯一看到的好处是,当序列迭代器返回代理引用时,您需要以非常量方式对该引用进行操作.例如,请考虑:

The only advantage I can see is when the sequence iterator returns a proxy reference and you need to operate on that reference in a non-const way. For example consider:

#include <vector>

int main()
{
    std::vector<bool> v(10);
    for (auto& e : v)
        e = true;
}

这不会编译,因为从iterator返回的右值vector<bool>::reference不会绑定到非常量左值引用.但这会起作用:

This doesn't compile because rvalue vector<bool>::reference returned from the iterator won't bind to a non-const lvalue reference. But this will work:

#include <vector>

int main()
{
    std::vector<bool> v(10);
    for (auto&& e : v)
        e = true;
}

所有这些,除非您知道需要满足这种用例,否则我不会这样编码. IE.我不会无缘无故地这样做,因为它确实使人们想知道您在做什么.如果我确实这样做了,那么就为什么添加评论是没有害处的:

All that being said, I wouldn't code this way unless you knew you needed to satisfy such a use case. I.e. I wouldn't do this gratuitously because it does cause people to wonder what you're up to. And if I did do it, it wouldn't hurt to include a comment as to why:

#include <vector>

int main()
{
    std::vector<bool> v(10);
    // using auto&& so that I can handle the rvalue reference
    //   returned for the vector<bool> case
    for (auto&& e : v)
        e = true;
}

修改

我的最后一个案例确实应该是一个有意义的模板.如果您知道循环始终在处理代理引用,则auto将与auto&&一样工作.但是当循环有时处理非代理引用,有时处理代理引用时,我认为auto&&将成为首选解决方案.

This last case of mine should really be a template to make sense. If you know the loop is always handling a proxy reference, then auto would work as well as auto&&. But when the loop was sometimes handling non-proxy references and sometimes proxy-references, then I think auto&& would become the solution of choice.

这篇关于在基于范围的for循环中使用转发引用有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 01:18