auto - C++11, 2 of n

来源:互联网 发布:java socket 发送byte 编辑:程序博客网 时间:2024/06/07 03:13
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

原创粉丝点击