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

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

问题描述

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

  1. 从返回时是否涉及复制/移动(没有 RVO)生成元组?
  2. 它是否会导致未定义的行为?
  3. 我可以读写通用参考.可以 auto&&无功 =func() 总是使用而不是 auto var = func() 以便没有复制/移动?
  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. 是的.任何不返回引用类型的函数的返回都可能涉及复制/移动.消除这就是 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.

没有.为什么要呢?绑定到引用的临时/纯右值的生命周期由引用的范围决定.

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;&`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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