Consider this code:
struct foo
{
static constexpr int value = 42;
};
void bar(const int* value) { std::cout << *value; }
int main() { bar(&foo::value); }
This compiles fine and without warnings under the couple of online compilers I tried. Given that there is no single .cpp
file defining the constexpr
value, could the value of the pointer be different if the bar
method is invoked from different compilation units? Or does the standard guarantee that the value ends up allocated only one time across all compilation units (ie an implicit _declspec(selectany)
)?
Everyone knows the memory location tables of C and C++ programs. For operating systems, executable code and all the static variables get copied from the hard drive disc into the allocated areas of text, static ect. in the RAM.
The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.
A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type. Each of its parameters must be of a literal type.
#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.
It doesn't work for me---I get a linker error. http://coliru.stacked-crooked.com/a/59e2cf56122733d0
If you do not odr-use the static constexpr member, you can imagine that it's inlined wherever required and doesn't live in any compilation unit. If you do odr-use it, as you have done in your program, you must define it.
The other answers are correct but the situation will change in C++17, with the adoption of inline variables (p0386). constexpr will then imply inline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With