当一个值是非常量但用常量表达式初始化时使用constexpr

Using constexpr when a value is non-const but initialized with a constant expression?

本文关键字:常量 表达式 constexpr 初始化 是非 一个      更新时间:2023-10-16

由于某些原因,我很难掌握如何正确使用constexpr

标题中描述的情况是否适合使用?即:

void foo()
{
static constexpr const size_t MAX_BUFFER_SIZE = 20 * 1024 * 1024;
constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression
std::vector<char> buffer(bufferSize, ' ');
//...
if (some_condition())
{
bufferSize = get_random_value_at_runtime(); // Assigned a new 'non-constexpr' value
buffer.resize(bufferSize, ' ');
}
//...   
}

谨致问候!

标题中描述的情况是否适合使用?

错误。

constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression
// ...
bufferSize = get_random_value_at_runtime(); 

CCD_ 2暗示(也是(CCD_。

不能重新分配const变量。