由于某些原因,我很难掌握如何正确使用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
变量。