In C ++ using auto advantages and note

First, the advantages

(A) avoid forget initialization

Forget writing C ++ initialization bug often lead to difficult to find, and use auto avoided this risk, because, like auto x;this statement by the compiler is not - not even initialized, the compiler can not deduce xthe type of .

(B) avoid the pit

Sometimes forget is what type of data structure used contained in the end is that we expected and actual type is not the same type. For chestnuts, if you have a high pursuit of efficiency, then the following code can not achieve this make you satisfied with the results:

unordered_map<int, int> m ({ {1,1}, {2,2} });
do_sth (const pair<int, int>& p);//将m的元素作为实参

This code was intended by-reference parameter passing avoid duplication, improve efficiency, but in fact this code is running or the argument is copied again. Because the elements of unordered_map pair <const key, value> type, the compiler of the first pair <const key, value> value type of the copy operation, generates a temporary variable pair <key, value> type, then pwith this temporary variable binding. If the function above code instead of a signature const auto& p, it can be directly bound.
In order to verify the correctness of this above described, we verify the following codes:

unordered_map<int, int> m ({ {1,1}, {2,2} });//unordered_map的元素为pair<const key, value>类型
//对auto_p取址会得到*m.begin()的地址
const auto& auto_p = *m.begin();
//若上面的描述正确,那么对p取址会得到临时变量的地址,它与auto_p的取址结果不同
const pair<int, int>& p = *m.begin();
//将取址结果转化为int储存起来
int p_address = (int)&p, auto_p_address = (int)&auto_p;

if (p_address == auot_p_address)
    cout << "t";
else
    cout << "f";

Output is f, the above description is described correctly.
Another method is to avoid the pit view a document or source code .

(C) the simple reconstruction

If one day need to int xbe changed long long x, only you need to change the value on it.

Second, the use of attention

(A) derivation typically ignored typed reference

Do not type on derived content look. For example, when using the auto return type, even as a function return arr[i], the return value is not referenced.

(B) the invisible proxy class

For example, vector<bool>::operator []return the vector<bool>::referencetype of the other objects (vector Nested in a class). As another example, some of the C ++ class library uses expression templates. At this time, it will lead to the use of auto type, and we expect to get are not the same.

The solution is to: 1. view the document or the source code to find out whether the presence of the agent class. 2. Use static_cast Type conversion to ensure that the type of get what we want.

Guess you like

Origin www.cnblogs.com/saltedreed/p/12043717.html