auto(C++11~C++17)

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 约定规定函数参数是从左往右依次压入堆栈中,由被调用方负责清理堆栈。在实际编程中,我们通常不需要显式地指定函数的调用约定,编译器会根据平台和编译选项自动选择适合的约定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值