C++11

自动类型推断(auto关键字):C++11引入了auto关键字,可以根据变量初始值自动推导出变量类型。例如:

1

2

auto i = 42;  // i被推导为int类型

auto d = 3.14;  // d被推导为double类型

基于范围的for循环(range-based for loop):可以方便地遍历容器中的元素,例如:

1

2

3

4

std::vector<int> v = {1, 2, 3, 4, 5};

for (auto& i : v) {

    i *= 2;

}

lambda表达式:lambda表达式可以用来定义匿名函数,方便地传递函数对象,例如:

1

2

auto f = [](int x, int y) -> int { return x + y; };

int result = f(3, 4);  // result = 7

移动语义和右值引用(move semantics和rvalue references):通过右值引用可以实现资源的有效移动而不是复制,提高程序的效率,例如:

1

2

std::vector<int> v1 = {1, 2, 3, 4, 5};

std::vector<int> v2 = std::move(v1);  // v2接管了v1的资源,v1变为无效状态

智能指针(smart pointers):C++11引入了三种智能指针:unique_ptr、shared_ptr和weak_ptr,可以更好地管理动态内存,避免内存泄漏和悬空指针,例如:

1

2

3

std::unique_ptr<int> p(new int(42));

std::shared_ptr<int> q = std::make_shared<int>(42);

std::weak_ptr<int> r = q;

空指针常量(nullptr):C++11引入了nullptr关键字,用于表示空指针,避免了NULL宏带来的一些问题,例如:

1

2

void f(int* p) {}

f(nullptr);  // 可以显式地传递空指针

右值引用与移动构造函数:右值引用可以方便地实现移动构造函数和移动赋值运算符,用于高效地处理临时对象和避免复制开销,例如:

1

2

3

4

5

6

7

8

9

10

class MyVector {

public:

    MyVector(MyVector&& other) noexcept {

        // 移动构造函数

    }

    MyVector& operator=(MyVector&& other) noexcept {

        // 移动赋值运算符

        return *this;

    }

};

初始化列表:可以方便地初始化数组和容器,例如:

1

2

std::vector<int> v = {1, 2, 3, 4, 5};

std::map<std::string, int> m = {{"one", 1}, {"two", 2}, {"three", 3}};

类型别名(type alias):可以使用using关键字定义类型别名,例如:

1

2

using IntVec = std::vector<int>;

IntVec v = {1, 2, 3, 4, 5};

模板别名(template alias):可以使用using关键字定义模板别名,例如:

1

2

3

template <typename T>

using Vec = std::vector<T>;

Vec<int> v = {1, 2, 3, 4, 5};

constexpr函数和变量:可以在编译期计算出值,例如:

1

2

3

4

constexpr int fib(int n) {

    return (n <= 1) ? 1 : fib(n-1) + fib(n-2);

}

constexpr int x = fib(10);  // 编译期计算出x的值为89

变长参数模板(variadic templates):可以接受任意数量和类型的参数,例如:

1

2

3

4

5

6

template <typename... Args>

void print(Args... args) {

    std::cout << sizeof...(args) << std::endl;  // 打印参数个数

}

print(1, 2, 3);  // 打印3

print("hello", 3.14);  // 打印2

C++14

泛型lambda表达式:可以使用auto关键字在lambda表达式中推断参数类型,例如:

1

2

3

auto sum = [](auto x, auto y) { return x + y; };

std::cout << sum(1, 2) << std::endl;  // 输出3

std::cout << sum(1.5, 2.5) << std::endl;  // 输出4.0

return type deduction for normal functions(函数返回类型推断):可以使用auto关键字让编译器自动推断函数的返回类型,例如:

1

2

3

auto add(int x, int y) {

    return x + y;  // 返回类型会自动推断为int

}

模板变量(template variable):可以使用关键字template定义模板变量,例如:

1

2

3

template <typename T>

constexpr T pi = T(3.1415926535897932385);

std::cout << pi<double> << std::endl;  // 输出3.14159...

静态断言(static_assert)的增强:可以在静态断言中加入一个字符串提示,例如:

1

static_assert(sizeof(int) == 4, "int必须是4字节");  // 如果sizeof(int)不等于4,会输出提示信息

字符串字面量的增强:可以使用单引号(')包围字符,例如:

1

2

constexpr char operator""_c(char c) { return c; }  // 将字符转化为字符

std::cout << 'a'_c << std::endl;  // 输出字符'a'

按值捕获的增强:可以使用关键字init来对按值捕获的变量进行初始化,例如:

1

2

3

int x = 1, y = 2;

auto f = [x, y = x + 1] { return x + y; };

std::cout << f() << std::endl;  // 输出4

变量模板(variable template):可以使用关键字template定义变量模板,例如:

1

2

3

template <typename T>

constexpr T pi = T(3.1415926535897932385);

std::cout << pi<double> << std::endl;  // 输出3.14159...

内存模型的增强:增加了对内存模型的规定,例如:

1

2

3

4

5

6

std::atomic<int> x = 0;  // 原子变量

#pragma omp parallel for

for (int i = 0; i < 1000; ++i) {

    x.fetch_add(1);  // 线程安全的对x进行加一操作

}

std::cout << x << std::endl;  // 输出1000

C++17

结构化绑定(Structured Binding):可以使用auto关键字对一个结构体或元组进行结构化绑定,例如:

1

2

3

std::pair<int, int> p = {1, 2};

auto [x, y] = p;  // 结构化绑定

std::cout << x << " " << y << std::endl;  // 输出1 2

if语句和switch语句的初始化:可以在if语句和switch语句的判断条件中进行变量初始化,例如:

1

2

3

if (int x = get_value(); x > 0) {  // 在if语句中初始化变量x

    std::cout << "x is positive" << std::endl;

}

类模板的参数推断(Class Template Argument Deduction,CTAD):可以让编译器自动推断类模板的模板参数,例如:

1

std::pair p{1, 2};  // 编译器可以自动推断出std::pair<int, int>

constexpr if:可以在编译期进行条件判断,根据判断结果选择不同的代码路径,例如:

1

2

3

4

5

6

7

8

template <typename T>

void foo(T t) {

    if constexpr (std::is_pointer_v<T>) {  // 如果T是指针类型

        std::cout << "t is a pointer" << std::endl;

    } else // 如果T不是指针类型

        std::cout << "t is not a pointer" << std::endl;

    }

}

折叠表达式(Fold Expression):可以使用折叠表达式来简化代码,例如:

1

2

3

4

5

template <typename... Args>

auto sum(Args... args) {

    return (args + ...);  // 对args进行折叠求和

}

std::cout << sum(1, 2, 3, 4) << std::endl;  // 输出10

内联变量(Inline Variable):可以使用inline关键字来定义内联变量,例如:

1

inline int x = 1;  // 定义一个内联变量x,初始值为1

嵌套命名空间(Nested Namespace):可以在命名空间中嵌套命名空间,例如:

1

2

3

4

5

6

7

8

namespace A {

    namespace B {

        void foo() {

            std::cout << "hello, world!" << std::endl;

        }

    }

}

A::B::foo();  // 调用函数foo

C++20

概念(Concepts):概念是一种新的语言结构,可以用来描述模板参数的要求,例如:

1

2

3

4

5

6

7

template <typename T>

concept Integral = std::is_integral_v<T>;

template <typename T>

void foo(T t) requires Integral<T> {  // 使用概念描述模板参数要求

    std::cout << t << std::endl;

}

foo(1);  // 调用foo函数

三方合并运算符(Three-way Comparison Operator):可以使用<=>运算符对两个对象进行三方比较,例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

struct Point {

    int x, y;

    auto operator<=>(const Point& other) const {

        return std::tie(x, y) <=> std::tie(other.x, other.y);

    }

};

bool operator==(const Point& lhs, const Point& rhs) {

    return lhs.x == rhs.x && lhs.y == rhs.y;

}

std::set<Point> s{{1, 2}, {2, 1}, {1, 1}, {2, 2}};

for (const auto& p : s) {

    std::cout << p.x << ", " << p.y << std::endl;

}

输出结果为:

1, 1
1, 2
2, 1
2, 2

初始化的捕获列表(Init-Capture):可以在lambda表达式的捕获列表中进行初始化,例如:

1

2

3

4

5

int x = 1;

auto lambda = [value = x * 2]() {  // 在捕获列表中初始化变量value

    std::cout << value << std::endl;

};

lambda();  // 调用lambda表达式

consteval函数:可以在编译期计算表达式的值,例如:

1

2

consteval int get_value() { return 42; }  // 定义一个在编译期计算的函数

std::array<int, get_value()> arr;  // 在编译期创建一个大小为42的数组


 

更多推荐