C++ 中未命名命名空间的使用 [英] Uses of unnamed namespace in C++

查看:84

问题描述

什么时候会在 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.

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆