C++ 11特性示例代码

  • 初始化列表,这个基本没啥可讲的
#include <iostream>
#include <vector>
#include <functional>

struct Point {
private:
    float x;
    float y;
public:
    Point(std::initializer_list<float> list) {
        x = *list.begin();
        y = *(list.begin() + 1);
    }

    float getX() { return x; }

    float getY() { return y; }
};

int main() {
    std::vector<int> nums = {3, 4};
    nums.push_back(3);
    Point point = {3.0, 4.0};
    std::cout << "(" << point.getX() << "," << point.getY() << ")" << std::endl;
    return 0;
}

 

  • lambda

需要注意的是func和func2的输出并不相同,因为func2对局部变量的引用是值传递,在定义函数的时候,就会把值拷贝到函数定义中,所以输出是50。如果把func2的定义挪到consumer执行之后,输出会变成0。对于func因为用的是引用传递,所以以上两种情况输出都是0。这像极了js和java。

#include <iostream>
using namespace std;

int main() {
    int a = 4, b = 5;
    function<int(void)> supply = [=]() -> int {
        return a;
    };
    function<void(int)> consumer = [&](int in) {
        a = 0;
        b = 0;
        cout << "consuming value: " << b << endl;
    };
    function<int(int)> func = [&](int in) -> int {
        return in * b;
    };
    function<int(int)> func2 = [=](int in) -> int {
        return in * b;
    };
    cout << "value from supply is: " << supply() << endl;
    cout << "a and b are: " << a << ", " << b << endl;
    consumer(9);
    cout << "a and b are: " << a << ", " << b << endl;
    cout << "value from supply is: " << func(10) << endl;
    cout << "a and b are: " << a << ", " << b << endl;
    cout << "value from supply is: " << func2(10) << endl;
    cout << "a and b are: " << a << ", " << b << endl;
    return 0;
}
  • 移动语义和RVO
  • 编译器的优化还是蛮有意思,如下代码,返回将调用拷贝构造函数,因为返回的对象是不确定的。但如果改成注释的方式,也就是无论如何都返回局部变量dog,因为返回是确定的,并且是一个局部变量,则不会发生拷贝构造。但是对于传入的参数,即使直接返回,也会进行拷贝构造。
  • 
    Dog getDog(Dog &param) {
        Dog dog;
        if (param.getName() == "dog1") {
            dog = Dog("xxx");
            return dog;
        }/* else{ 
            dog = param;
        }
        return dog;
        */
        return param;
    }

     

  1. https://www.jianshu.com/p/dcd3390c5c84
  2.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值