C++11 auto vs auto& vs auto&&

auto and auto && cover most of the cases:

  • Use auto when you need a local copy. This will never produce a reference. The copy (or move) constructor must exist, but it might not get called, due to the copy elision optimization.

  • Use auto && when you don't care if the object is local or not. Technically, this will always produce a reference, but if the initializer is a temporary (e.g., the function returns by value), it will behave essentially like your own local object.

    Also, auto && doesn't guarantee that the object will be modifiable, either. Given a constobject or reference, it will deduce const. However, modifiability is often assumed, given the specific context.

auto & and auto const & are a little more specific:

  • auto & guarantees that you are sharing the variable with something else. It is always a reference and never to a temporary.

  • auto const & is like auto &&, but provides read-only access.

What about for primitive/non-primitive types?

There is no difference.

Does this also apply to range based for loops?

Yes. Applying the above principles,

  • Use auto && for the ability to modify and discard values of the sequence within the loop. (That is, unless the container provides a read-only view, such as std::initializer_list, in which case it will be effectively an auto const &.)
  • Use auto & to modify the values of the sequence in a meaningful way.
  • Use auto const & for read-only access.
  • Use auto to work with (modifiable) copies.

You also mention auto const with no reference. This works, but it's not very commonly used because there is seldom an advantage to read-only access to something that you already own.


Reference

http://stackoverflow.com/questions/29859796/c-auto-vs-auto

  • 12
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EnjoyCodingAndGame

愿我的知识,成为您的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值