0

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!

max66
  • 65,235
  • 10
  • 71
  • 111
not an alien
  • 651
  • 4
  • 13

1 Answers1

8

Is the situation described in the title an appropriate place to use it?

Wrong.

constexpr size_t bufferSize = 1024 * 1024; // Initialized with constant expression

// ...

    bufferSize = get_random_value_at_runtime(); 

constexpr implies (is also) const.

You can't re-assign a const variable.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
max66
  • 65,235
  • 10
  • 71
  • 111
  • Interesting, reading answers from [Difference between `constexpr` and `const`](https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const) made me think they are completely independent from one another. – not an alien Oct 30 '18 at 14:45
  • 2
    @notanalien In your linked answer it has *When can I / should I use both, const and constexpr together? A. In object declarations. This is never necessary when both keywords refer to the same object to be declared. constexpr implies const.* Which is the same as what max66 said. – NathanOliver Oct 30 '18 at 14:47
  • 1
    @notanalien - they can be indipendent when they are used for methods (member functions) of structs/classes, but only starting from C++14; in C++11 `constexpr` methods are also `const`. Anyway, a `constexpr` variable is ever (also C++14 and C++17) also `const`. – max66 Oct 30 '18 at 17:38