mardi 30 octobre 2018

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

For some reason I have a hard time grasping how to correctly use constexpr.

Is the situation described in the title an appropriate place to use it? i.e:

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

    //...   
}

Kind regards!

Aucun commentaire:

Enregistrer un commentaire