Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which compilation unit lives a constexpr variable?

Tags:

c++

constexpr

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))?

like image 408
Trillian Avatar asked Jul 14 '16 18:07

Trillian


People also ask

Where are constexpr variables stored?

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.

What is a constexpr variable?

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.

What is a constexpr function?

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.

When to use #define vs constexpr?

#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.


2 Answers

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.

like image 96
Brian Bi Avatar answered Oct 06 '22 01:10

Brian Bi


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.

like image 45
Fabio Fracassi Avatar answered Oct 05 '22 23:10

Fabio Fracassi