C++23新增特性

C++ core feature!

cplusplus语言特性

核心语言特性

自动推导 this(Deduced this)

C++23 允许 this 类型从成员函数推导,把”自引用”从模板约束里抠出来,成员函数可以直接写 this。

struct Counter {
    int value = 0;

    void increment(this Counter& self) {
        self.value += 1;
    }
};

Counter c;
c.increment();
c.increment();
static_assert(c.value == 2, "");

更自由的 consteval / 常量求值

C++23 放宽 consteval(要求它可在常量表达式上下文中调用)与 constexpr 的组合,让”只能做编译期计算”的函数能更大范围参与编译期求值。

consteval int compute(int x) {
    int r = 1;
    for (int i = 2; i <= x; ++i) r *= i;
    return r;
}

static_assert(compute(5) == 120, "");

标准库特性

std::expected<T, E>:带错误的期望值

C++23 上线 std::expected,返回 value 或 error(替代了散落在各种 API 里的 exception 或 error code 的混合写法),是函数式风格错误处理的主干。

std::expected<int, std::string> lookup(const std::string& key) {
    if (key == "42") return 42;
    return std::unexpected<std::string>("not found");
}

auto n = lookup("42");
if (n) {   // n.has_value(),也可 n.value()
    auto v = *n;   // v == 42
}

std::mdspan:多维 Span

std::span 是一维连续视图,C++23 的 std::mdspan 把它放进”多维”(行列数组语义),适合数值计算与图形。

auto matrix = std::mdspan<int, std::extents<2>>{1, 2, 3, 4};
matrix[0][1];   // 2

std::at<T>:带检查的访问

std::vector::at 的命名版,越界抛异常而非 UB — 防御性库编程的实心注入。

std::vector<int> v{1, 2, 3};
v.at(0);    // OK
v.at(99);   // std::out_of_range

更多 range 算法与 unordered 成员

  • std::ranges::to_* 系列(如 to_vector, to_unordered_set)将视图/容器转出算法;
  • std::unordered_set::contains / contains 统一了”查找”语义。

其它

  • char8_t 相关字符串类型继续推进,UTF-8 字符串成为一等公民;
  • 文本编码、IO 性能等配套改动跟进中。

参考