C++11标准赋予了auto的含义:声明变量时根据初始化表达式自动推断该变量的类型、声明函数时函数返回值的占位符
使用auto和万能引用声明变量时(见第6章),对于左值会将auto推导为引用类型:
int i = 5;
auto&& m = i; // auto推导类型为int& (这里涉及引用折叠的概念)
auto&& j = 5; // auto推导类型为int
2. 什么时候使用auto?
2.1 一眼就可以看出声明变量的初始化类型的时候
std::map<std::string, int> str2int = { {"one", 1}, {"two", 2}, {"three", 3} };
// … 填充str2int的代码
for (std::map<std::string, int>::const_iterator it = str2int.cbegin();
it != str2int.cend(); ++it) {
}
for (const std::pair<std::string, int>& it : str2int) {
//std::cout << "key: " << key << ", value: " << value << std::endl;
}
改为
std::map<std::string, int> str2int = { {"one", 1}, {"two", 2}, {"three", 3} };
// … 填充str2int的代码
for (auto it = str2int.cbegin();
it != str2int.cend(); ++it) {
}
for (auto it : str2int) {
}
2.2 对于复杂的类型,例如lambda表达式、bind等直接使用auto
auto l = [](int a1, int a2) { return a1 + a2; };
auto b = std::bind(sum, 5, std::placeholders::_1);
3. lambda表达式中使用auto
使用lambda表达式返回auto引用的地址(C+++14)
auto l = [](int &i)->auto& { return i; };
auto x1 = 5;
auto &x2 = l(x1);
assert(&x1 == &x2); // 有相同的内存地址
注意
__cdecl 是一种函数调用约定(calling convention),它规定了函数参数的传递方式、堆栈的清理方式等等。在 __cdecl 约定下,函数的参数是从右往左依次压入堆栈中,由调用方负责清理堆栈。这与默认的 stdcall 约定不同,stdcall 约定规定函数参数是从左往右依次压入堆栈中,由被调用方负责清理堆栈。在实际编程中,我们通常不需要显式地指定函数的调用约定,编译器会根据平台和编译选项自动选择适合的约定。