[英]Using constexpr when a value is non-const but initialized with a constant expression?
由於某些原因,我很難掌握如何正確使用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();
constexpr
暗示(也是) const
。
您不能重新分配const
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.