C++11新特性总述
C++11新特性总述

C++11 是 C++ 语言的一次重大更新,增加了大量的新特性,使得语言更现代、更高效、更安全。下面是 C++11 的主要新特性分类和简介:


🔹 1. 自动类型推导与类型相关

  • auto:让编译器自动推导变量类型。

    1auto x = 5; // int
    
  • decltype:根据表达式推导类型。

    1decltype(x) y; // y 的类型和 x 相同
    
  • 新的函数返回类型写法(尾返回类型):

    1auto func() -> int;
    

🔹 2. 智能指针

  • std::unique_ptr:独占所有权。

  • std::shared_ptr:共享所有权,引用计数。

  • std::weak_ptr:弱引用,防止循环引用。


🔹 3. 右值引用与移动语义

  • 引入 T&&(右值引用),支持 移动构造函数移动赋值运算符,提高性能。

    1std::vector<int> v1 = {1,2,3};
    2std::vector<int> v2 = std::move(v1); // v1 被移动
    

🔹 4. lambda 表达式

用于定义匿名函数,尤其适合回调、STL 算法等场景。

1auto f = [](int x) { return x * 2; };
2std::cout << f(10); // 输出 20

🔹 5. 并发支持

  • std::thread:创建线程。

  • std::mutexstd::lock_guard:互斥锁。

  • std::asyncstd::future:异步任务处理。


🔹 6. 范围 for 循环

1std::vector<int> v = {1,2,3};
2for (auto x : v) {
3    std::cout << x << std::endl;
4}

🔹 7. 初始化列表(std::initializer_list

1std::vector<int> v = {1, 2, 3}; // 统一初始化

🔹 8. 强类型枚举

1enum class Color { Red, Green, Blue }; // 不会隐式转换为整数

🔹 9. nullptr 替代 NULL

1int* p = nullptr; // 明确表示空指针

🔹 10. constexpr(编译期常量)

1constexpr int square(int x) { return x * x; }

🔹 11. 静态断言(static_assert

1static_assert(sizeof(int) == 4, "int必须是4字节");

🔹 12. 统一的列表初始化语法

1struct Point { int x, y; };
2Point p = {1, 2};

🔹 13. 新标准库特性

  • std::to_string

  • std::array

  • std::unordered_map, std::unordered_set

  • std::tuple



最后修改于 2025-04-27 18:22