简体   繁体   English

命名空间中的const全局变量

[英]const global variable in namespace

I know that static const class members can be initialised in headers only. 我知道static const class成员只能在头文件中初始化。 Is it the same for namespaces ? 命名空间是否相同? For example, is it valid to write : 例如,写入是否有效:

namehuman.hpp

namespace namehuman
{
   string const human("human");
}

main.cpp

#include "namehuman.hpp"
cout << namehuman::human << endl;

I am wondering if all files including the header file will have their own copy of string human, or if human will be a true global variable (not copied many times). 我想知道包括头文件在内的所有文件是否都有自己的string人类副本,或者人类是否是真正的全局变量(不会多次复制)。 In order to avoid each including file making its copy, am I obliged to use extern ? 为了避免每个包含文件的副本,我是否有义务使用extern

Constants have internal linkage. 常量具有内部联系。 Thus any compilation unit that includes the header with the definition of the constant will have its own instance of the object. 因此,任何包含带有常量定义的头的编译单元都将拥有自己的对象实例。

According to the C++ Standard (3.5 Program and linkage) 根据C ++标准(3.5程序和链接)

3 A name having namespace scope (3.3.6) has internal linkage if it is the name of 3具有命名空间范围(3.3.6)的名称具有内部链接(如果它的名称)

... ...

— a non-volatile variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; - 一个非易失性变量,显式声明为const或constexpr,既未显式声明为extern,也未声明为具有外部链接; or 要么

If you want a constant with external linkage, you must declare it with the specifier extern , and define it in a compilation unit. 如果需要具有外部链接的常量,则必须使用说明符extern声明它,并在编译单元中定义它。

I think that will define the human several times, so it can happen that this causes an ODR violation (see below). 我认为这将多次定义human ,因此可能会导致ODR违规(见下文)。 It's usually best to only declare it in the header 通常最好只在标题中声明它

extern const string human;

and add the definition to the implementation file 并将定义添加到实现文件中

string human("human");

Be careful about the initialization order fiasco and the equivalent when closing the application. 关闭应用程序时,请注意初始化顺序fiasco和等效项。

An ODR violation can be caused when an inline function with external linkage ODR-uses human . 当具有外部链接ODR的内联函数使用human时,可能会导致ODR违规。 I think that, since that is really easy to do and there is no way to guard against it, it is best to define constant strings in the implementation file. 我认为,由于这很容易做到并且没有办法防范它,最好在实现文件中定义常量字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM