What compilation unit does the constexpr variable live in?

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 warning in the online compilers section I tried. Given that there is no single .cpp file that defines the value of constexpr , can the pointer value be different if the bar method is called from different compilation units? Or does the standard guarantee that the value will be allocated only once for all compilation units (i.e. Implicit _declspec(selectany) )?

+5
source share
3 answers

This does not work for me --- I get a linker error. http://coliru.stacked-crooked.com/a/59e2cf56122733d0

If you are not using any static constexpr element, you can imagine that it is embedded where necessary and does not live in any compilation unit. If you use odr-use, as it was in your program, you must define it.

+9
source

Other answers are correct, but the situation will change in C ++ 17, with the adoption of built-in variables (p0386) . constexpr will mean inline.

+4
source

In general, the address of an object is odr-use, which requires the object to be defined somewhere (causing linker errors if it is not). However, address selection may not be considered odr-use if the resulting expression is a discarded value. Perhaps your use of this may be handled by some compilers as part of this exception, as it is passed as a parameter to a function that immediately discards it.

+1
source

All Articles