C++23 新特性详解:相较于 C++20 的主要改进
C++23 是 C++ 编程语言的最新标准版本(截至 2023 年),它在 C++20 的基础上引入了许多重要的新特性和改进。以下是 C++23 相较于 C++20 的主要变化:
一、语言核心特性改进
1. if consteval 语句
允许在编译时和运行时选择不同的代码路径
cpp
constexpr int foo() {
if consteval { // C++23 新增
return 42; // 编译时执行
} else {
return runtime_value(); // 运行时执行
}
}
2. 多维下标运算符
支持自定义多维数组的下标访问方式
cpp
struct Matrix {
int data[10][10];
// C++23 允许这样定义
int& operator[](size_t i, size_t j) {
return data[i][j];
}
};
Matrix m;
m[2, 3] = 42; // 多维下标访问
3. 静态运算符 operator[] 支持静态下标
cpp
struct FixedString {
constexpr char operator[](size_t N) const {
return data[N];
}
const char* data;
};
constexpr FixedString fs{"hello"};
static_assert(fs[1] == 'e'); // C++23 支持
4. 放宽 constexpr 限制
- 允许在
constexpr函数中使用typedef和using - 允许在
constexpr函数中使用dynamic_cast和typeid - 允许在
constexpr上下文中更灵活地使用union
二、标准库增强
1. 新的标准库模块
cpp
import std; // C++23 标准库模块
2. <mdspan> 多维数组视图
cpp
#include <mdspan>
int data[2 * 3 * 4] = {...};
std::mdspan mat(data, 2, 3, 4); // 3D视图
int val = mat[1, 2, 3]; // 多维访问
3. <print> 格式化输出
cpp
#include <print>
std::print("Hello {}!\n", "world"); // 类型安全、更快的输出
std::println("Value: {}", 42); // 自动换行
4. 堆栈追踪库 <stacktrace>
cpp
#include <stacktrace>
void foo() {
auto trace = std::stacktrace::current();
std::cout << std::to_string(trace) << '\n';
}
5. <expected> 错误处理
cpp
#include <expected>
std::expected<int, std::string> parse_number(std::string_view s) {
try {
return std::stoi(std::string(s));
} catch (...) {
return std::unexpected("parse error");
}
}
6. 范围(Ranges)增强
- 新增
ranges::to用于范围转换 - 新增
ranges::fold用于范围折叠操作 - 更多范围适配器如
chunk_by,slide,join_with
cpp
auto vec = std::views::iota(1, 6) | std::ranges::to<std::vector>();
三、并发编程改进
1. std::hive (原 plf::colony)
非连续容器,适合高频插入删除场景
cpp
#include <hive>
std::hive<int> h;
auto it = h.insert(42);
h.erase(it); // 不影响其他迭代器有效性
2. std::atomic 增强
std::atomic<float>和std::atomic<double>支持更多操作- 新增
std::atomic_ref对非原子对象的原子操作
cpp
float f = 3.14f;
std::atomic_ref af(f);
af.store(2.71f);
四、其他重要改进
1. 字符串格式化增强
cpp
std::string s = std::format("{:m}", 1048576); // 可能输出 "1 MiB"
2. 类型系统增强
std::is_scoped_enum检测有作用域枚举std::to_underlying将枚举转换为基础类型
cpp
enum class Color { Red, Green, Blue };
static_assert(std::is_scoped_enum_v<Color>);
int val = std::to_underlying(Color::Red);
3. 模块改进
- 模块分区增强
- 更好的模块与头文件互操作性
4. 协程增强
- 协程工具类型如
std::coroutine_traits改进 - 协程调试支持更好
五、移除或弃用的特性
- 移除了
std::aligned_storage和std::aligned_union - 弃用了
std::shared_ptr的unique()成员函数 - 移除了对一些旧 C 库函数的兼容支持
六、总结
C++23 在 C++20 的基础上主要带来了以下方面的改进:
- 语言核心 :更灵活的
constexpr、多维下标、静态运算符等 - 标准库 :新增
<mdspan>,<print>,<stacktrace>等重要组件 - 并发 :
std::hive容器和原子操作增强 - 工具性:更好的格式化输出、错误处理和调试支持
- 现代化:进一步推动模块、范围和协程的使用
这些改进使 C++23 成为更强大、更安全、更易用的版本,特别是在高性能计算、系统编程和并发编程领域。