未命名的命名空间对全局变量有什么影响?
这两个源文件有什么区别?
namespace { int var; }
// or
int var;
如果两者都放在 cpp 文件中,我们将变量放在未命名的命名空间中以便它可以仅对该文件是私有的,这是不正确的吗?但是,如果我们将全局变量放入 cpp 文件中,该变量不是也是私有的吗,因为您从不包含 .cpp 文件?
What is the difference between these two in a source file?
namespace { int var; }
// or
int var;
if both are put in the cpp file, is not correct that we put a variable in an unnamed namespace so it can be private for just that file? But if we put a global variable in a cpp file is not that variable also private because you never do an include to .cpp file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在第二种情况下,当您不使用匿名名称空间时,如果任何其他 cpp 文件声明
extern int var;
,它将能够使用您的变量。如果使用匿名命名空间,那么在链接时,另一个 cpp 文件将生成未定义的引用错误。
In your second case, when you don't use an anonymous namespace, if any other cpp file declares an
extern int var;
, it will be able to use your variable.If you use an anonymous namespace, then at link time, the other cpp file will generate an undefined reference error.
在第二种情况下,其他
.cpp
文件可以访问该变量:并且链接器将找到它。在第一种情况下,变量名称因任何原因而被破坏:),因此上述情况是不可能的。
In the second case other
.cpp
files can access the variable as:and the linker will find it. In the first case the variable name is mangled beyond any reason :) so the above is not possible.
来访问它
第二个版本是在全局命名空间中定义的——其他 .cpp 文件可以通过声明extern int var;
,即使他们不这样做,如果其他人在全局名称空间,您将收到链接错误(多重定义的符号)。
The second version is defined in the global namespace -- other .cpp files can get to it by declaring
extern int var;
and even if they don't do that, if someone else uses the same name in the global name space, you'll get a link error (multiply defined symbol).
除了 Nikolai 等人给出的原因之外,如果不使用匿名命名空间,则可能会与其他全局数据发生命名冲突。如果您确实使用匿名命名空间,则会隐藏全局数据。
来自 cprogramming.com:“在命名空间内,您可以放心,没有全局名称会发生冲突因为每个命名空间的函数名称优先于外部函数名称。”
In addition to the reason given by Nikolai and others, if you don't use an anonymous namespace, you can get naming conflicts with other global data. If you do use an anonymous namespace, you will instead shadow the global data.
From cprogramming.com: "Within the namespace you are assured that no global names will conflict because each namespace's function names take precedence over outside function names."
两点:
标准中规定:
Two points:
extern int var;
can access your variable if it's not in an unnamed namespace.int var
global variable, you will have multiple definitions of this variable.As specified in the standard :