简体   繁体   English

在C ++中使用未命名的命名空间

[英]Uses of unnamed namespace in C++

When would one use unnamed namespace in C++ ? 何时在C ++中使用未命名的命名空间? Is it better in any sense than a free standing function? 在任何意义上它比独立功能更好吗? Also, should it be used only in source file and not in header file? 是否应该仅在源文件中使用而不在头文件中使用?

According to Stroustrup, you should use it in places where in old C you would have made static globals. 根据Stroustrup的说法,你应该在老C的地方使用它来制作static全局变量。 The idea is that the items in question can be "global" to the source file they are in, but not pollute the namespace of any other source files in your compilation. 这个想法是有问题的项目可以是它们所在源文件的“全局”,但不会污染编译中任何其他源文件的命名空间。

In other words, you shouldn't be creating static globals in C++ . 换句话说, 您不应该在C ++中创建static全局变量 You should be using unnamed namespaces instead. 您应该使用未命名的命名空间。

I have found some situations where they are useful in header files, but that should be rare. 我发现了一些在头文件中有用的情况,但这种情况应该很少见。 Mostly I think for declaring throwable exceptions. 我认为主要用于声明可抛出的异常。 In that case the definitions in question will be global for everything that #include s that header, but not for things that don't. 在这种情况下,所讨论的定义对于#include s标题的所有内容都是全局的,但对于没有标题的内容则不是。

Unnamed namespace is private to the translation unit and this can be used to shield global variables and functions with same names occurring in different translation units so that no link conflicts arise. 未命名的命名空间对于翻译单元是私有的,这可以用于屏蔽在不同翻译单元中出现的具有相同名称的全局变量和函数,从而不会出现链接冲突。

For example, you need a class that will only be defined in a .cpp file and used only within that file. 例如,您需要一个只在.cpp文件中定义并仅在该文件中使用的类。 You want to call it CModuleLock . 你想称之为CModuleLock If it is not in an unnamed namespace and some other .cpp file accidentially has another class CModuleLock not in an unnamed namespace you won't be able to link your program. 如果它不在未命名的命名空间中,并且某个其他.cpp文件意外地具有另一个类CModuleLock不在未命名的命名空间中,则您将无法链接您的程序。

It's used for name hiding. 它用于名称隐藏。 Each unnamed namespace is unique. 每个未命名的命名空间都是唯一的。 The link here explains in more detail. 这里的链接更详细地解释。 It is typically used in a source file to hide functions that should only have internal linkage (eg not exposed to the outside world). 它通常用在源文件中,以隐藏只应具有内部链接的函数(例如,不暴露给外部世界)。

基本上,命名空间解决了相同名称类,标识符和函数之间的冲突。有关更多信息,请单击下面的链接https://simplifiedtutorial4u.blogspot.in/2017/08/what-is-namespace-in-c。 HTML

Unnamed namespaces are the "C++ version" of global static variables and functions. 未命名的命名空间是全局静态变量和函数的“C ++版本”。 Note that you can also use a unnamed namespace for classes. 请注意,您还可以为类使用未命名的命名空间。

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

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