use of constexpr in header file

后端 未结 4 716
情话喂你
情话喂你 2021-01-31 09:06

I can have a definition like this in a header file?

 constexpr double PI=3.14;

Is there any problem in having this in a header file that would

4条回答
  •  滥情空心
    2021-01-31 09:56

    constexpr implies const and const on global/namespace scope implies static (internal linkage), which means that every translation unit including this header gets its own copy of PI. The memory for that static is only going to be allocated if an address or reference to it is taken, and the address is going to be different in each translation unit.

    That implied static for const variables was introduced specifically to use const instead of #define in header files in C++ to define constants. Without static there would be multiple symbol definitions linker error if that header file is included in more than one translation unit which were linked together.

    In C++17 you can also make it inline, so that there is only ever a single copy of PI if an address or reference to it is taken (i.e. not static). inline variables were introduced in C++17 to allow for header-only libraries with non-const variable definitions in the header files. constexpr on static data members implies inline, so inline is unnecessary there.

    In other words, you should use constexpr for your constants in header files, if possible, otherwise const. And if you require the address of that constant to be the same everywhere mark it as inline.

提交回复
热议问题