Uses of unnamed namespace in C++(C++ 中未命名命名空间的使用)
问题描述
什么时候会在 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.
我发现在一些情况下它们在头文件中很有用,但这种情况应该很少见.大多数情况下,我认为是为了声明可抛出的异常.在这种情况下,所讨论的定义对于 #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 #includes that header, but not for things that don't.
这篇关于C++ 中未命名命名空间的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中未命名命名空间的使用
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
