const 与 constexpr 的区别及应用场景 ​

面试考点 ​

这是 C++ 面试中出现频率非常高的基础题。面试官想考察的是:你是否真正理解"不可变"和"编译期常量"之间的区别,以及在实际代码中怎么选择用哪个。

核心区别 ​

const 表示"值初始化后不可修改",但这个值可以在运行时才确定。constexpr 表示"值必须在编译期就能确定",它同时也隐含了 const 的含义。

一句话总结:所有 constexpr 变量都是 const 的,但不是所有 const 变量都是 constexpr 的。

cpp
#include <iostream>
#include <cstdlib>
#include <array>

// ============================
// 基本区别演示
// ============================

void basic_difference() {
    // const:值不可修改,但可以在运行时初始化
    const int runtime_val = std::rand();  // OK:运行时确定
    // runtime_val = 10;  // 编译错误:不能修改 const 变量

    // constexpr:值必须在编译期确定
    constexpr int compile_val = 42;       // OK:编译期常量
    // constexpr int bad = std::rand();   // 编译错误:std::rand() 不是常量表达式

    // constexpr 可以用在需要编译期常量的地方
    int arr[compile_val];                  // OK:数组大小需要编译期常量
    std::array<int, compile_val> stdarr;   // OK:模板参数需要编译期常量

    // const 只有在用编译期常量初始化时才能用于这些场景
    const int n = 10;
    int arr2[n];                           // OK:n 用字面量初始化,是编译期常量

    // 但这个 const 不行
    // int arr3[runtime_val];              // 错误:runtime_val 不是编译期常量
}

对比表 ​

特性constconstexpr
含义值不可修改值必须编译期可求值
初始化时机编译期或运行时必须编译期
隐含关系不隐含 constexpr隐含 const
用于数组大小仅当用常量表达式初始化时始终可以
用于模板参数仅当用常量表达式初始化时始终可以
可修饰函数成员函数(表示不修改成员)函数(表示可在编译期求值)
可修饰指针指针本身或指向的值指针本身(顶层 const)

基本示例 ​

cpp
#include <iostream>
#include <array>
#include <type_traits>

// ============================
// 示例1:变量声明
// ============================

void variable_demo() {
    // 1. const 变量
    const int a = 10;          // 编译期常量(因为用字面量初始化)
    const int b = a + 5;       // 编译期常量(a 是编译期常量)

    int x = 42;
    const int c = x;           // 运行时常量(x 不是编译期常量)

    // 2. constexpr 变量
    constexpr int d = 10;      // 编译期常量
    constexpr int e = d + 5;   // 编译期常量
    // constexpr int f = x;    // 编译错误:x 不是常量表达式

    // 3. 用于需要编译期常量的场景
    std::array<int, d> arr1;   // OK
    std::array<int, a> arr2;   // OK(a 恰好是编译期常量)
    // std::array<int, c> arr3; // 错误:c 不是编译期常量
}

// ============================
// 示例2:constexpr 函数
// ============================

// constexpr 函数:如果参数是编译期常量,结果也是编译期常量
constexpr int square(int n) {
    return n * n;
}

// const 不能用来修饰普通函数(只能修饰成员函数)
// const int bad_func(int n) { return n * n; }  // const 修饰返回值,不是函数

void function_demo() {
    // 编译期调用
    constexpr int result1 = square(5);   // 编译期计算,result1 = 25
    static_assert(square(5) == 25);       // 编译期断言

    // 运行时调用
    int x = 7;
    int result2 = square(x);             // 运行时计算

    std::cout << "square(5) = " << result1 << std::endl;
    std::cout << "square(7) = " << result2 << std::endl;
}

// ============================
// 示例3:const 成员函数
// ============================

class Circle {
    double radius_;
public:
    // 构造函数
    Circle(double r) : radius_(r) {}

    // const 成员函数:承诺不修改对象状态
    double area() const {
        return 3.14159265358979 * radius_ * radius_;
    }

    // 非 const 成员函数:可以修改对象状态
    void set_radius(double r) {
        radius_ = r;
    }

    // constexpr 成员函数:可以在编译期求值
    constexpr double get_radius() const {
        return radius_;
    }
};

void member_function_demo() {
    Circle c(5.0);
    std::cout << "面积: " << c.area() << std::endl;

    const Circle cc(3.0);
    std::cout << "面积: " << cc.area() << std::endl;
    // cc.set_radius(4.0);  // 编译错误:const 对象不能调用非 const 成员函数
}

// ============================
// 示例4:constexpr 构造函数
// ============================

struct Point {
    double x, y;

    // constexpr 构造函数:允许在编译期创建对象
    constexpr Point(double x, double y) : x(x), y(y) {}

    // constexpr 成员函数
    constexpr double distance_squared() const {
        return x * x + y * y;
    }
};

void constexpr_class_demo() {
    // 编译期创建对象
    constexpr Point p(3.0, 4.0);
    constexpr double dist_sq = p.distance_squared();

    static_assert(dist_sq == 25.0);  // 编译期验证

    std::cout << "距离平方: " << dist_sq << std::endl;
}

// ============================
// 示例5:const 指针 vs constexpr 指针
// ============================

void pointer_demo() {
    int a = 10;
    int b = 20;

    // const 修饰指针有两种含义
    const int* p1 = &a;       // 指向 const int 的指针(底层 const)
    // *p1 = 100;             // 错误:不能通过 p1 修改值
    p1 = &b;                  // OK:可以改变指向

    int* const p2 = &a;       // const 指针指向 int(顶层 const)
    *p2 = 100;                // OK:可以修改值
    // p2 = &b;               // 错误:不能改变指向

    const int* const p3 = &a; // 两层都是 const

    // constexpr 指针:指针本身是编译期常量(顶层 const)
    static int s = 42;        // 静态变量,地址编译期可知
    constexpr int* p4 = &s;   // constexpr 修饰指针本身
    *p4 = 100;                // OK:可以修改指向的值
    // p4 = &a;               // 错误:不能改变指向

    // 注意:constexpr 只对指针本身施加 const,不影响指向的值
    constexpr const int* p5 = &s;  // 指针和值都不可修改
}

// ============================
// 示例6:constexpr if(C++17)
// ============================

template<typename T>
void print_type_info(const T& val) {
    // constexpr if 在编译期决定分支
    if constexpr (std::is_integral_v<T>) {
        std::cout << val << " 是整数类型" << std::endl;
    } else if constexpr (std::is_floating_point_v<T>) {
        std::cout << val << " 是浮点类型" << std::endl;
    } else {
        std::cout << "其他类型" << std::endl;
    }
}

void constexpr_if_demo() {
    print_type_info(42);
    print_type_info(3.14);
    print_type_info("hello");
}

int main() {
    std::cout << "=== 变量 ===" << std::endl;
    variable_demo();

    std::cout << "\n=== 函数 ===" << std::endl;
    function_demo();

    std::cout << "\n=== 成员函数 ===" << std::endl;
    member_function_demo();

    std::cout << "\n=== constexpr 类 ===" << std::endl;
    constexpr_class_demo();

    std::cout << "\n=== constexpr if ===" << std::endl;
    constexpr_if_demo();

    return 0;
}

面试高频追问 ​

问:constexpr 函数一定在编译期执行吗?

不一定。constexpr 函数在参数是编译期常量时在编译期执行;如果参数是运行时的值,它就退化为普通函数在运行时执行。

问:const 引用可以绑定到临时对象吗?

可以。const int& ref = 42; 是合法的,const 引用会延长临时对象的生命周期。非 const 引用不能绑定临时对象。

问:constexpr 和 consteval 有什么区别?

constexpr 函数可以在编译期或运行时执行。consteval(C++20)函数必须在编译期执行,如果在运行时调用会直接报编译错误。

问:const 成员函数里可以修改成员变量吗?

正常情况不可以。但如果成员变量被声明为 mutable,则可以在 const 成员函数中修改。

适用场景 ​

  • 用 const:函数参数表示不修改、成员函数表示不改变对象状态、局部变量标记不可修改
  • 用 constexpr:数组大小、模板参数、编译期计算、static_assert 条件、switch case 值

注意事项 ​

  • constexpr 变量必须用常量表达式初始化
  • constexpr 隐含 const,不需要写 constexpr const
  • constexpr 指针的 const 是顶层的(修饰指针本身),不是底层的(不修饰指向的值)
  • C++14 放宽了 constexpr 函数的限制(可以有循环、局部变量等)
  • C++17 引入了 if constexpr,在编译期做分支选择
  • C++20 引入了 consteval(必须编译期)和 constinit(必须编译期初始化但运行时可修改)

总结 ​

const 和 constexpr 都能让值不可修改,但本质不同。const 只保证"初始化后不能改",值可以在运行时确定。constexpr 保证"值必须在编译期就能确定",可以用在数组大小、模板参数等需要编译期常量的地方。选择原则:如果值在编译期就知道,优先用 constexpr;如果值要到运行时才能确定,用 const。面试中要能说清楚:所有 constexpr 都是 const,但不是所有 const 都是 constexpr;constexpr 函数不一定在编译期执行;const 成员函数通过 mutable 可以修改特定成员。