C++20新特性_consteval 和 constinit

文章目录

  • [第一章 C++20核心语法特性](#第一章 C++20核心语法特性)
    • [1.7 consteval 和 constinit](#1.7 consteval 和 constinit)
      • [1.7.1 consteval 和 constinit作用](#1.7.1 consteval 和 constinit作用)
      • [1.7.2 示例](#1.7.2 示例)
      • [1.7.3 const constexpr consteval constinit 对比](#1.7.3 const constexpr consteval constinit 对比)

本文记录C++20新特性之consteval 和 constinit。

第一章 C++20核心语法特性

1.7 consteval 和 constinit

在 C++11 引入 constexpr 之后,编译期计算(Compile-time Computation)的大门被彻底打开。但是,constexpr 有时过于"宽容"------它既可以在编译期运行,也可以在运行期运行,这导致了语义上的模糊。

为了更精准地控制编译期行为,C++20 引入了两个新的关键字:consteval 和 constinit。它们分别解决了"强制编译期执行"和"强制编译期初始化"这两个痛点。

1.7.1 consteval 和 constinit作用

consteval 告诉编译器,只能在编译期间计算。

constinit:告诉编译器,修饰的变量只能在编译期间确定好。

1.7.2 示例

cpp 复制代码
    // consteval 声明:此函数必须在编译期完成计算
    consteval int sqr(int n) {
        return n * n;
    }

    void test()
    {
        // 1 传入编译期常量,
        constexpr int r1 = sqr(33);

		// 2 传入 constexpr
		constexpr int x = 5;
        constexpr int r2 = sqr(x);

        // 3 传入非编译期常量,编译错误
        int y = 10;
		//int r3 = sqr(y); // 编译错误:必须在编译期求值

    }

示例2:测试 constinit

cpp 复制代码
    constexpr int get_initial_value()
    {
        return 42;
    }

    // 1. constinit 保证 global_x 在编译期完成初始化
    // 2. global_x 依然是可变的 (mutable)
    constinit int global_x = get_initial_value();

    // 错误示例:
    int runtime_val = 100;
    // constinit int err_val = runtime_val; // 编译错误!必须用常量表达式初始化

    int test()
    {
        std::cout << "Initial: " << global_x << std::endl; // 输出 42

        // 修改变量
        global_x = 100;
        std::cout << "Modified: " << global_x << std::endl; // 输出 100

        return 2;
    }

1.7.3 const constexpr consteval constinit 对比

对比:

相关推荐
普通网友6 天前
记录我适配iOS26遇到的一些问题
c++20
前进吧-程序员7 天前
C++20/23 Ranges:从「迭代器对」到「可组合管道」
c++20
ComputerInBook7 天前
C++ 关键字 constexpr 和 consteval 之注意事项
开发语言·c++·constexpr·consteval
Shan120511 天前
实例分析:C++20的std::jthread
c++20
charlie11451419111 天前
基于开源项目的现代C++工程实践——OnceCallback 前置知识(下):C++20/23 高级特性
c++·开源·c++20
Hical_W12 天前
Hical 踩坑实录五部曲(二):MSVC / GCC / Clang 三平台 C++20 编译差异
linux·windows·经验分享·嵌入式硬件·macos·开源·c++20
Shan120513 天前
C++20中带有约束条件的new
c++20
Hical_W16 天前
用 Hical + MySQL 5 分钟搭建 CRUD API(C++20 协程版)
数据库·mysql·c++20
Hical_W16 天前
从 io_context 出发,掌握 C++20 协程式异步 I/O,学会 TCP 服务器、定时器和多线程模型,结合 Hical 框架实战解读
服务器·tcp/ip·开源·c++20
c++之路21 天前
C++20概述
java·开发语言·c++20