当值是 non-const 但使用常量表达式初始化时使用 constexpr?

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, ' ');
    }

    //...   
}

亲切的问候!

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 变量。