NDK14_C++基础:部分C++11、14特性

NDK开发汇总

nullptr

nullptr 出现的目的是为了替代 NULL。 C++11之前直接将NULL定义为 0。

void test(int* i){
    
}
void test(int i){
    
}
//现在调用哪一个test? test(int)
test(NULL);
//调用test(int* i)
test(nullptr); 

类型推导

C++11 重新定义了auto 和 decltype 这两个关键字实现了类型推导,让编译器来操心变量的类型。

auto i = 5;             // i 被推导为 int
auto p = new auto(10) // arr 被推导为 int *
//但是auto不能作用在数组上
auto arr1[10] = { 0 }; //错误
auto arr2= {0}; //正确
typeid(arr2).name() //获得类型名为 initializer_list(后续介绍)
// int  j
decltype(i) j = 10;

基于范围的 for 循环

实际上就是foreach

vector<int> vec = { 1,2,3,4,5 };
//配合auto使用
for(auto i : vec)
{
	cout << i << endl;
}

Lambda

匿名函数,即没有函数名的函数

完整形式:

[捕获外部变量列表 ] (参数列表) mutable exception->返回类型 { 函数体 }

mutable:在外部变量列表以值来捕获时,无法修改变量的值,加上mutable表示可修改(不会影响外部变量)

auto i = 5;
// [&] 表示外部变量都以引用的形式在lambda中使用,函数内部修改i的值会影响外部
// 这里的 -> auto 自动推导在c++11不支持,c++14中对auto进行了扩展
thread t1([&] () -> auto {
	i = 100;
	cout << "线程:" << i  << endl;
});
_sleep(10);
cout << i << endl;
捕获形式 说明
[] 不捕获任何外部变量
[i, …] 以值得形式捕获指定的多个外部变量(用逗号分隔);如果引用捕获,需要显示声明&
[this] 以值的形式捕获this指针
[=] 以值的形式捕获所有外部变量
[&] 以引用形式捕获所有外部变量
[=, &x] 变量x以引用形式捕获,其余变量以传值形式捕获
[&, x] 变量x以值的形式捕获,其余变量以引用形式捕获

猜你喜欢

转载自blog.csdn.net/baopengjian/article/details/106786805