- 初始化列表,这个基本没啥可讲的
#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 ¶m) { Dog dog; if (param.getName() == "dog1") { dog = Dog("xxx"); return dog; }/* else{ dog = param; } return dog; */ return param; }