问题描述
什么时候在C ++中使用未命名的命名空间?它在任何意义上比自由职能更好吗?
When would one use unnamed namespace in 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?
推荐答案
根据Stroustrup,你应该使用它在旧C中,您将创建 static
全局变量的地方。想法是,有问题的项目可以是全局的源文件,但不会污染编译中任何其他源文件的命名空间。
According to Stroustrup, you should use it in places where in old C you would have made static
globals. 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.
换句话说,您不应在C ++中创建 static
全局变量。您应该使用未命名的命名空间。
In other words, you shouldn't be creating static
globals in C++. You should be using unnamed namespaces instead.
我发现一些情况下,他们在头文件中有用,但这应该是罕见的。大多数情况下,我认为声明throwable异常。在这种情况下,所涉及的定义对于 #include
的所有头部是全局的,而不是不是的东西。
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.
这篇关于C ++中未命名命名空间的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!