出于某种原因,我很难掌握如何正确使用 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, ' ');
}
//...
}
亲切的问候!
最佳答案
Is the situation described in the title an appropriate place to use it?
错了。
constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression
// ...
bufferSize = get_random_value_at_runtime();
constexpr
暗示(也是)const
。
您不能重新分配 const
变量。
关于c++ - 当值是非常量但使用常量表达式初始化时使用 constexpr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53066712/