6

Despite reading through some StackOverflow posts (this and this) and cppreference pages, I cannot figure out how a non-static constexpr local variable would be beneficial compared to a static constexpr one.

The only difference I can see is that each invocation would have its own instance, but since it's a constexpr I don't see the practical advantage here (since, if I understand correctly, that'd cause each instance to be identical and immutable, making multiple instances simply redundant).

Or, to argue from another point: Since non-static constexpr locals are initialized at (every) function invocation, there is no advantage to a simple const local, despite that it may be used for compile-time evaluations. But when they are needed for compile-time evaluation, there's no point in making them not static.

So my question is: How is my argument deficient, and in what cases would a non-static constexpr local variable be reasonable and possibly be the best choice?

Reizo
  • 1,374
  • 12
  • 17
  • There would be no difference from practical view. – SergeyA Jul 09 '20 at 19:17
  • 1
    Remember that since C++11, static variables are guaranteed to have thread safe initialization. That means they are going to cost you every time you call the function, since it needs to make the check to see if it was initialized. A non-static constexpr variable is just going to grow the stack (if it even does as it could be optimized away), which is extremely cheap and fast. – NathanOliver Jul 09 '20 at 19:18
  • The last paragraph of the answer https://stackoverflow.com/a/13867690/1023911 gives some hints when not to use `static`. – Werner Henze Jul 09 '20 at 19:19
  • @WernerHenzeyes, thank you. I Indeed read that but to me it was not convincing enough to not make me still wonder. – Reizo Jul 09 '20 at 19:34
  • @NathanOliver this situation seems quite particular to me. I was looking for something more 'ordinary'. But of course you have a valid point there. – Reizo Jul 09 '20 at 19:38
  • I'm not even sure that there's an advantage to actually having the variable in the first place, since the RHS needs to be `constexpr` as well. If you just use the RHS somewhere in the function, the compiler can compute it at compile-time anyway and turn it into a constant. The only case I can think of where you would want it to be a variable is if you use it multiple times in the function and don't want to duplicate the RHS, or if you need to take a pointer to it. – cdhowie Jul 09 '20 at 22:20

0 Answers0