auto - C++11, 2 of n

C++11 redefines the meaning of "auto" keyword, it saves typing, but more importantly seamlessly supports for lambda and  template argument deduction. Lambda itself has no type.

There are some tricks related to "auto", mastering the following semantics, you already are the expert!

1) Saves typing.
     const int x = 0;
     auto y = x;
     auto z = 1;

2) Sometimes, you don't know what the type it is.
  auto f = []->int(int val) {

                     return val * 2;

                   };

3) auto by value.
  for(auto s1: v)
  {
  }

What is the difference from the following ?
  for(string s2: v)
  {
  }

Answer: they are the same.
a) s1/2 is a modifiable copy, v can be modifiable or const
b) s1 is modifiable even v is const; "auto" drop constness.

4) auto by const value.
  for(const auto s1: v)
  {
  }

What is the difference from the following ?
  for(const string s2: v)
  {
  }

Answer: they are the same.
a) s1/2 is a const copy. v can be modifiable or const.

5) auto by reference.
  for(auto& s1: v)
  {
  }
What is the difference from the following when v is modifiable?
  for(string s2&: v)
  {
  }

Answer: they are the same.
a) Observe/modify s1 in place, if v is modifiable.
b) Observe s1 in place, if v is const.
c) s1 is const if v is const, "auto &" preserve constness.

6) auto by const reference
  for(const auto& s1: v)
  {
  }
What is the difference from the following ?
  for(const string s2&: v)
  {
  }

Answer: they are the same.
a) Observe s1/2 in place, v can be modifiable or const.

7) Which of the following is fast ?
vector<string> v;
for (const auto& s1 : v)
for (const string& s2 : v)
// They're identical!

map<string, int> m;
for (const auto& p1 : m)
for (const pair<string, int>& p2 : m)
// const auto& p1 is faster!
// m's value_type is pair<const string, int>
// Binding const pair<string, int>& to pair<const string, int>
//     constructs a temporary pair<string, int>,
//     which copies a string.

8) The rule: 95% of the time, you should use:
a) for (auto& e : r)
b) for (const auto& e : r)

9) Why would you want to use anything else?
a) When you actually want a copy
     for (auto e : r) // intentional copy
b) When you actually want a conversion
     for (uint64_t x : r) // uint32_t => uint64_t
c) When proxies might be involved
    for (auto&& e : r) // binds to everything

10) What the hell is "auto &&" ? Type deduction + reference collapsing rules apply here.

Reference:

http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/STL11-Magic-Secrets

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值