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 对比

对比:

相关推荐
Lzg_na7 天前
C++20 Concept 核心概念、语法详解与三大工程实践场景
c++20
Billy121387 天前
Day14-C++20 Modules:模块声明与导入、模块分区、与头文件对比、迁移策略
c++20·c++进阶学习
程序猿编码7 天前
不用GPU,不用多线程,我用C++20手写了一个Gemma 3推理引擎
pytorch·语言模型·大模型·c++20·推荐算法
Billy121389 天前
Day15-C++20 三路比较运算符 `<=>`:一次定义,全面排序
c++20·c++进阶学习
A_cainiao_A16 天前
C++20:std::stop_source让线程说停就听
开发语言·c++20
小小龙学IT20 天前
C++20 Ranges 库实现原理深度解析:从视图适配器到管道运算符
c++20
Billy1213823 天前
C++20 Concepts:约束与概念的现代范式
c++20·c++进阶学习
可爱系程序猿24 天前
mfc90.dll 缺失如何处理?VC++ 2008 运行库与并行程序集排查记录
程序人生·电脑·c++20
code_pgf24 天前
C++11 / C++14 / C++17 / C++20 新特性总结
c++·c++20
C语言Plus1 个月前
C++ SqlBuilder一个简单、灵活且类型安全的 C++ SQL 构建器库
数据库·sql·安全·c++20