I've been reading a book about C++14/11. I just finished reading a chapter about the constexpr
keyword. I know what it's used for, but how often should I use constexpr
? Should I use it even in code for classes I know will never be used to create contstexpr
objects? (Just in case, because it doesn't cost me anything, right?)
C++14 How often should I use constexpr?
There's an extensive discussion in item 15 (Use constexpr whenever possible) of the Scott Meyer's book Effective Modern C++.
The outline of this item is that constexpr
should be used whenever possible, due to the fact that constexpr
functions and objects can be used in a wider range of contexts than the non-constexpr
ones.
However, in the same item the author mentions a caveat of overusing constexpr
. That is, if you decide to qualify an object or a function as constexpr
your clients will be allowed to use it in constexpr
contents. However, if you later decide that this code must not be constexpr
and remove constexpr
, this can cause your code not to compile including the side effects that this will have to your clients.
Quoting from original text:
“Use constexpr whenever possible” is your willingness to make a long-term commitment to the constraints it imposes on the objects and functions you apply it to.
Google's C++ Style Guide suggests:
Use constexpr to specify true constants and the functions that support their definitions. consteval may be used for code that must not be invoked at runtime. Avoid complexifying function definitions to enable their use with constexpr. Do not use constexpr or consteval to force inlining.
It is important to note that without the static
keyword, using constexpr
on local variables can lead to some performance issues with large arrays. They might be initialized at runtime rather than storing them as data in the executable. constexpr
doesn't imply static
, only const
.
A white paper called Don't constexpr All The Things mentions further drawbacks including the complex set of rules necessary to mark a function as constexpr
.
A pragmatic approach might be to limit the usage of constexpr
keyword to only compile time functions and variable declarations that support those functions. Marking variables not used in compile time functions as constexpr
instead of const
has limited usefulness, unless it can be proven that the compiler will output better assembly.
© 2022 - 2024 — McMap. All rights reserved.