现代C++的10个新特性

132 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第17天,点击查看活动详情

C++ 经久不衰,效率高,速度快,功能强大,跨平台、至今依然还在不断演进。C++是一个非常难精通的语言,语法细节琐碎,

1-C++演变.jpg

委托构造函数 Delegating Constructors

在旧版本的 C++ 中是不允许在一个构造函数中调用另外一个构造函数的,但是在 C++ 11 中加入了委托构造函数.

我们在 Test 类中定义了两个构造函数,如果希望在后面这个构造函数被调用时,也自动调用前面的构造函数做一些初始化。使用类成员变量初始化的初始化列表。

class Test {
public:
    Test(int n) {}
    Test() {} : Test(0) {}
};

int main() { return 0; }

类内初始化 In-class Initialize

在以前的程序中,如果要对结构体或者是类成员变量进行初始化,我们需要使用初始化列表或者构造函数。但是在 C++11 之后,这些成员变量的初始化已经可以使用,类似于普通变量初始化的语法了!将变量的初始化和变量的定义写在一起,方便阅读和修改。

struct Data {
    int i = 1;
    float f = 2.0;
    bool b = true;
};

空指针 nullptr

通常情况下,我们使用 NULL 来表示空指针,但是这样使用有个缺点。因为 C++ 是一个强类型的语言,编译时的类型检查可以帮我们找到许多粗心的错误。所以 NULL 还可以 赋值给 int,float,虽然合法,但是不合适!

枚举类 enum class

在使用时前面加入枚举类名,可以有效的避免命名冲突。

enum class Number { One, Two, Three };
int main() {
    Number num = Number::One;
    return 0;
}

类型推导 Type Inference

auto 这个关键字是 C++11里面添加的新特性,让编译器自动帮我们推导类型,其次,auto 也可以作为返回值类型。

#include <iostream>
#include <vector>using namespace std;
​
int main(){
    vector<pair<int, int>> numbers = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
    
    for (auto it = numbers.cbegin(); it != numbers.cend9); it++){
        cout<<it->first<< ", "<<it->second<<endl;
    }
    return 0;
}

常量表达式 constexpr

将运行时的运算提到编译时来做性能优化,除此之外, constexpr 可以修饰任何的表达式。

初始化列表 Initializer List

#include <set>
#include <vector>using namespace std;
​
int main() {
    vector<set<int>> v = { {1, 2}, {3, 4, 5}};
    return 0;
}

基于范围的 for 循环 Range-Based For-Loops

#include <set>
#include <vector>
​
using namespace std;
​
int main() {
    map<int, string> numMap = {{1, "one"}, {2, "two"}, {3, "three"}};
    
    for(auto [key, val] : numMap){
        cout<<key<<"->"<<val<<endl;
    }
    return 0;
}

智能指针之 unique ptr

C++上一个存在一个问题就是内存泄露,如果你使用 new 一个内存,但是使用完之后并没有使用 delete 释放内存,就容易造成内存泄露。

我们不需要手动调用 delete 来销毁这个对象,当函数执行完成之后,这个对象的内存就会自动释放。

#include <memory>
using namespace std;
struct SomeData {
    int a, b, c;
};
​
void f() {
    auto data = make_unique<SomeData>();
    data->a = 1;
    data->b = 2;
    data->c = 3;
}

Lambda 表达式 Lambda Expression

就是用很简洁的语法快速的定义一个临时的匿名函数

#include <algorithm>
#inlcude <iostream>
#inlcude <vector>using namespace std;
​
int main() {
    vector<int> nnums = {1, 2, 3, 4, 5};
    auto it = find_if(nums.begin(), nums.end(), [](int x) { return x % 2 == 0;});
    cout<<"The first odd number is "<<*it;
    return 0;
}