本文介绍了在头文件中使用constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在头文件中有一个这样的定义吗?

  constexpr double PI = 3.14; 

在包含在多个cpp文件中的头文件中是否存在任何问题? / p>

我担心,因为它在标准中表示此constexpr具有自己的内存,将其放在标头中,然后将标头添加到多个cpp文件中,会生成相同的多个副本内存中的值和其他一些令人讨厌的问题。



我正在使用C ++ 11

解决方案

constexpr 表示 const const 全局/命名空间范围上的内容表示 static (内部链接),这意味着每个包含此标头的翻译单元都会获得自己的 PI 。仅在获取了该地址或对其引用的情况下,才会分配该静态内容的内存,并且每个翻译单元中的地址都将不同。



const 变量的隐式 static 专门用于使用 const 而不是C ++头文件中的 #define 来定义常量。没有 static ,如果该头文件包含在多个链接在一起的翻译单元中,则会出现多个符号定义链接器错误。



在C ++ 17中,您还可以使其成为内联,这样就只有<$ c的单个副本$ c> PI (如果已获取地址或引用)(即不是静态)。在C ++ 17中引入了 inline 变量,以允许在头文件中具有非常量变量定义的仅头文件库。静态数据成员上的 constexpr 表示 inline ,因此 inline



换句话说,如果可能,应该在头文件中使用 constexpr 作为常量,否则 const 。并且如果您要求该常量的地址在各处都相同,则将其标记为 inline


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 be included to several cpp files?

I am worried that since it says in standard that this constexpr has its own memory, putting it in header, and adding header to several cpp files, generate multiple copies of the same value in memory and some other nasty problems.

I am using C++11

解决方案

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.

这篇关于在头文件中使用constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:34