C++11
Standard introduces a new keywordauto
This keyword can automatically infer the type of the returned value through an expression, which is also one of the most widely supported features by compiler vendors in the new standard. Using this keyword can effectively reduce the code length, especially when using the template meta-programming.
A simple example:
Vector <map <int, string> stringMapArray; // Do not use auto version Vector <map <int, string >>:: iterator iter1 = stringMapArray. begin (); // Use auto version Auto iter2 = stringMapArray. begin (); |
Seeing such a short statement, I can no longer stand the first statement containing a large amount of redundant information. Therefore, the recently written C ++ is filled with auto everywhere, so you can use it in the lambda parameter list (unfortunately not ).
However, the abuse of auto makes a very hidden problem. When I recently wrote a regular expression engine, I found that the running efficiency is always lower than expected. At first I thought it was a problem of dynamic memory allocation. After I replace it with the memory pool, I found that although the efficiency has improved, but it still fails to meet the requirements. So I thought of the performance tool. After checking the tool, I found that the following statement took 70% of the time:
// Function declaration Set <int> & getSet (); Void foo () { // Takes up 70% of the time Auto s = getSet (); ... } |
Check to find the originalauto
Deduce the return value of the functionset<int>
Insteadset<int>&
This allows the set to be copied when the value is assigned, and the set contains more than 60 thousand pieces of data, which makes the reference operation that should have taken almost no time to become a time-consuming copy operation.
Checked the C ++ StandardISO/IEC 14882 Third edition P157The type inference of the auto keyword is actually the same as that of the template.
§ 7.1.6.4 auto specifier
If the list of declarators contains more than one declarator, the type of each declared variable is determined as described above. if the type deduced for the template parameter U is not the same in each deduction, the program is ill-formed.
const auto &i = expr;
The typei
Is the deduced type of the parameteru
In the callf(expr)
Of the following converted Ted function template:
template <class U> void f(const U& u);
Therefore, the previous expression is equivalent:
Set <int> & getSet (); Template <typename T> Void foo (T t ); Void bar () { // The parameter T here is inferred to set <int> instead of set <int> & Foo (getSet ()); } |
If we want to obtain the reference type, we need to explicitly write:
Auto & refValue = getSet (); |
After modification, the execution time of this statement has been reduced to negligible.
This lesson tells us how to useauto
It is easy, but you still need to carefully consider what the type is.