const强调不变性,constexpr强调编译时可确定性,所有constexpr都是const,但反之不成立;const变量可在运行时初始化,而constexpr必须在编译时求值;选择const用于运行期不变值,选择constexpr用于需编译时常量的场景如数组大小、模板参数或编译时计算,以提升性能和类型安全。

在C++中,
const
constexpr
constexpr
const
理解
const
constexpr
const
const
const
修饰变量: 这是最常见的用法。
const int max_attempts = 3; // 编译期常量 int user_input = getUserInput(); const int current_value = user_input; // 运行期常量
max_attempts
current_value
user_input
修饰指针和引用: 这是
const
const Type* ptr
Type const* ptr
int value = 10; const int* ptr_to_const = &value; // 可以指向非const变量,但不能通过ptr_to_const修改value // *ptr_to_const = 20; // 错误:不能修改const int value = 20; // 正确:value本身不是const
int value1 = 10; int value2 = 20; int* const const_ptr = &value1; // const_ptr 总是指向 value1 *const_ptr = 15; // 正确:可以通过const_ptr修改value1 // const_ptr = &value2; // 错误:不能改变const_ptr指向
int value = 10; const int* const const_ptr_to_const = &value; // *const_ptr_to_const = 20; // 错误 // const_ptr_to_const = &another_value; // 错误
const
const Type& ref
const
int x = 5; const int& ref_to_x = x; // ref_to_x = 10; // 错误 x = 10; // 正确,x本身不是const
修饰成员函数: 放在函数签名后面,表示这个成员函数不会修改对象的状态(即不会修改非静态成员变量)。
class MyClass {
public:
int get_value() const { // const成员函数
// value_++; // 错误:不能修改成员变量
return value_;
}
private:
int value_ = 0;
};这对于确保对象的不变性非常重要,尤其是在多线程环境中,或者当你将对象作为
const
constexpr
constexpr
修饰变量: 声明的变量必须在编译时就能确定其值。
constexpr int max_size = 100; // 编译时常量 // constexpr int runtime_value = getUserInput(); // 错误:getUserInput()是运行时函数
所有
constexpr
const
const
constexpr
修饰函数:
constexpr
constexpr int square(int n) {
return n * n;
}
int main() {
constexpr int s1 = square(5); // 编译时求值,s1 = 25
int x = 6;
int s2 = square(x); // 运行时求值,s2 = 36
// static_assert(square(4) == 16, "Compile-time check failed!"); // 编译时断言
}constexpr
return
if
constexpr
修饰构造函数: 允许在编译时创建类的实例。
class Point {
public:
constexpr Point(double x, double y) : x_(x), y_(y) {}
constexpr double get_x() const { return x_; }
constexpr double get_y() const { return y_; }
private:
double x_;
double y_;
};
constexpr Point p(10.0, 20.0); // 编译时创建对象总结:
const
constexpr
constexpr
const
const
constexpr
这确实是一个好问题,很多时候我也会在两者之间犹豫。在我看来,选择
const
constexpr
首先,一个基本原则是:如果一个变量的值在初始化后不应该改变,那就用 const
const
然后,再考虑
constexpr
constexpr
int arr[N];
N
template<int N> class MyContainer;
N
static_assert
我个人的习惯是,如果一个值是真正的“数学常量”或者“硬编码”的配置值,我会倾向于使用
constexpr
M_PI
const
有时候,我会先用
const
std::array
constexpr
constexpr
constexpr
const
“常量正确性”(
const
const
在我看来,掌握
const
提升代码可读性与意图表达: 当你看到一个函数参数是
const std::string& name
name
const
增强代码安全性,减少Bug:
const
const
const
促进编译器优化: 编译器知道一个变量是
const
const
const
改善API设计与接口契约: 在设计库或模块的公共接口时,
const
const
const
const
支持多线程编程: 虽然
const
const
const
mutable
const_cast
挑战与 mutable
尽管
const
const
const
这时,
mutable
mutable
const
class DataProcessor {
public:
int get_processed_data() const {
if (!cache_valid_) {
// 假设这里执行耗时计算,并更新cache_
// 尽管是const函数,但mutable成员可以修改
cache_ = expensive_computation();
cache_valid_ = true; // 修改mutable成员
}
return cache_;
}
private:
mutable int cache_; // 声明为mutable
mutable bool cache_valid_ = false; // 声明为mutable
int raw_data_;
};使用
mutable
const
const
mutable
mutable
总而言之,
const
const
constexpr
constexpr
constexpr
constexpr
最初在 C++11 中,
constexpr
return
C++11 限制(历史回顾):
return
if
switch
try-catch
C++14 及更高版本(更宽松,更实用):
if
switch
for
while
do-while
constexpr
new
delete
constexpr
throw
goto
尽管限制有所放宽,但核心思想不变:
constexpr
constexpr
正是由于其编译时求值的特性,
constexpr
编译时常量计算: 这是最直接的用途。任何可以在编译时完成的计算,比如阶乘、斐波那契数列、幂运算、单位转换等,都可以用
constexpr
constexpr long long factorial(int n) {
long long res = 1;
for (int i = 1; i <= n; ++i) {
res *= i;
}
return res;
}
// ...
constexpr long long f5 = factorial(5); // 编译时计算,f5 = 120
std::array<int, factorial(4)> arr; // 数组大小在编译时确定用于模板元编程:
constexpr
编译时字符串处理和哈希: 从 C++17 开始,
constexpr
std::string_view
switch
#include <string_view>
#include <stdexcept>
// 编译时字符串哈希函数
constexpr unsigned int string_hash(std::string_view s) {
unsigned int hash = 0;
for (char c : s) {
hash = (hash * 31) + c; // 简单的哈希算法
}
return hash;
}
// ...
switch (string_hash("command_a")) { // switch语句的case标签需要编译时常量
case string_hash("command_a"): // 编译时计算哈希值
// ...
break;
case string_hash("command_b"):
// ...
break;
default:
break;
}初始化 const
constexpr
const
constexpr
以上就是怎样声明和使用常量 const与constexpr关键字解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号