`static const` is a code smell
Channel
C++Weekly
Topics
static const variables look innocuous, but they can have subtle correctness and performance issues, especially for local (function scope) variables. We've been taught to constexpr all the things, and that static constexpr is the preferred form for local variables (see Ep 312). However, when static constexpr doesn't compile (because the right-hand side is not a constant expression), the average programmer might fall back to static const thinking it's the next best thing.
Here's an example correctness bug that static const causes:
void frobnicate(int value)
{
// twiddledValue is initialized with the first `value` passed in and never changes afterwards
static const auto twiddledValue = twiddle(value);
}
In terms of performance, the compiler often inserts a guard variable to protect the static variable's initialization, which adds some run-time overhead. (I'm not sure under which circumstances this occurs. Is it when the expression is not a "core constant expression" so it's not evaluated at compile time?)
Length
5-10 minutes
Isn't it already covered in episode 2: https://www.youtube.com/watch?v=B3WWsKFePiM ?
Isn't it already covered in episode 2: https://www.youtube.com/watch?v=B3WWsKFePiM ?
Fair enough. There might not be enough substance for another episode. I was thinking to cover it from the perspective of being deceptively similar-looking to static constexpr.