未命名的命名空间如何优于 static
关键字?
最佳答案
您基本上是指 C++03 标准中的第 7.3.1.1/2 节,
The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.
请注意,该段落已在 C++11 中删除。 static
函数已按标准不再被弃用!
不过,未命名的 namespace
优于 static 关键字,主要是因为关键字 static
仅适用于 variables 声明和函数,而不是用户定义的类型。
以下代码在 C++ 中有效:
//legal code
static int sample_function() { /* function body */ }
static int sample_variable;
但此代码无效:
//illegal code
static class sample_class { /* class body */ };
static struct sample_struct { /* struct body */ };
所以解决方案是,未命名(又名匿名)namespace
,就是这样:
//legal code
namespace
{
class sample_class { /* class body */ };
struct sample_struct { /* struct body */ };
}
希望它能解释为什么未命名的 namespace
优于 static
。
关于c++ - 未命名命名空间优于静态命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4422507/