o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K
C++新特性有哪些
- User
C++新特性有哪些
- Assistant
下面按标准版本(C++11/14/17/20/23)来梳理一下近几年引入的主要新特性,方便你快速了解:
1. C++11(2011)
- 自动类型推导:
auto x = 42; - 范围 for 循环:
for (auto& e : vec) { … } - Lambda 表达式:
auto f = [](int a, int b){ return a + b; }; - 智能指针:
std::unique_ptr,std::shared_ptr - 移动语义 & 右值引用:
T&&,std::move() - constexpr 函数/常量
- 强类型枚举:
enum class Color { Red, Green }; - 静态断言:
static_assert(sizeof(int)==4, "…"); - 线程库:
std::thread,std::mutex,std::future - 初始化列表:
std::vector<int> v = {1,2,3};
2. C++14(2014)
- 二进制字面量:
0b1010'1100 - 通用 lambda 捕获(init-capture):
[x = std::move(y)]{ … } - return type 自动推导(函数):
auto func()->int简化为auto func() - std::make_unique
- constexpr 增强(可以在函数中写更多语句)
3. C++17(2017)
- 结构化绑定:
auto [a,b] = pair; - if/switch 初始化语句:
if (auto it = m.find(k); it!=m.end()) { … } - 折叠表达式(Fold Expression):
template<typename... Ts> auto sum(Ts... ts){ return (ts + ...); } - inline 变量:
inline constexpr int N = 100; - std::optional / std::variant / std::any
- 文件系统库:
<filesystem> - 并行算法支持(
<algorithm>加入 execution policies) - constexpr 进一步增强(几乎可等同运行时)
4. C++20(2020)
- 概念(Concepts):对模板参数进行约束
- 范围(Ranges):
std::views::filter,std::views::transform等 - 协程(Coroutines):
co_await,co_yield - 三向比较运算符(Spaceship operator):
auto cmp = a <=> b; - 模块(Modules):替代传统
#include - consteval / constinit
- 扩展的 constexpr(几乎整个 STL 都可在编译期执行)
- 强化的字符字面量:
u8"…"、格式化字符串(std::format 在部分实现可用)
5. C++23(2023,部分编译器已支持)
- std::expected(类似于 Rust 的 Result)
- std::flat_map, std::flat_set
- 模板参数列表推导(deducing this)
- 三向比较支持更多类型
- 标准库算法与 ranges 的持续扩展
- 扩展的 JSON 支持(部分库实现)
示例:结构化绑定与 if 初始化(C++17)
#include <iostream> #include <map> #include <string> int main() { std::map<std::string,int> m {{"one",1}, {"two",2}}; // if 初始化 + 结构化绑定 if (auto it = m.find("two"); it != m.end()) { std::cout << "Found: " << it->first << " = " << it->second << "\n"; } // 结构化绑定遍历 for (auto const& [key, val] : m) { std::cout << key << " -> " << val << "\n"; } }以上只是大纲式的梳理,具体每个特性还有更深入的使用技巧和注意点。如果你对某条感兴趣,欢迎继续交流~ 😊
- 自动类型推导: