什么时候不使用`auto&&`? [英] When not to use `auto&&`?

查看:122
本文介绍了什么时候不使用`auto&&`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  auto&& mytup = std::make_tuple(9,1,"hello");
  std::get<0>(mytup) = 42;
  cout << std::get<0>(mytup) << endl;




  1. 返回时涉及复制/移动
    make_tuple?

  2. 是否导致未定义的行为?

  3. 我可以读写通用引用。可以自动&& var =
    func()
    总是使用而不是 auto var = func(),以便没有复制/移动? / li>
  1. Is there a copy/move involved (without RVO) when returning from make_tuple?
  2. Is it causing undefined behavior?
  3. I can both read write the universal reference. Can auto&& var = func() be used always instead of auto var = func() so that there is no copy/move?


推荐答案


  1. 是的。从不返回引用类型的函数的任何返回可能涉及复制/移动。 Eliding这就是RVO是什么。

  1. Yes. Any return from a function that does not return a reference type may involve a copy/move. Eliding that is what RVO is about. The object that your reference is bound to needs to be initialized somehow.

不需要。为什么要呢?绑定到引用的临时/ prvalue的生命周期由引用的范围确定。

No. why should it? The lifetime of a temporary/prvalue bound to a reference is determined by the scope of the reference.

如果func()不返回引用类型不应该是效率(也不是行为)的差异。

If func() does not return a reference type, there should not be any difference in efficiency (nor behaviour)

之间

auto&& var = func();

auto var = func();

在这两种情况下,都将构造一个包含生命周期到包含块结尾的对象。在一种情况下,它有自己的名称,在另一个它通过引用命名。在这两种情况下,名称都可以用作左值。 RVO在这两种情况下同样可以很好地应用。

In both cases an object with lifetime to the end of the containing block is constructed. In one case it has its own name, in the other it is named via a reference. In both cases the name can be used as an lvalue. RVO can be equally well applied in either case.

一些编译器可能优化一个局部对象而不是一个引用,即使在当前情况下,临时与本地对象没有什么区别。

Some compilers might optimize better for a local object than for a reference, even though in the current case the reference-to-temporary is really no different from a local object.

如果 func()可能会返回引用,则事情会有很大不同 - 在这种情况下,想要复制/移动或不移动。

If func() might return a reference, things are much different - in that case you must decide whether you want to copy/move or not.

这篇关于什么时候不使用`auto&amp;&amp;`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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