标准规定的具体含义是什么
$7.3.1.1/2 - "The use of the static keyword is deprecated when declaring variables in a namespace scope (see annex D); the unnamed-namespace provides a superior alternative."
我已推荐 this但它并没有涵盖我正在寻找的内容。
有没有一个例子清楚地证明了优越性。
注意:我知道未命名的命名空间如何使外部变量在翻译单元中可见,但对其他翻译单元隐藏它们。但这篇文章的重点是关于“静态命名空间范围”的名称(例如全局静态变量)
最佳答案
究竟是什么意思?
技术上已弃用意味着 future 的标准可能会删除该功能。
实际上这不会发生,因为需要支持旧代码。
所以在实践中它的意思是“强烈劝阻”。
未命名命名空间优越性示例
未命名的命名空间通常更好,因为您在该命名空间中的内容可以具有外部链接。
在 C++98 中,对于可以是模板参数的东西,外部链接是必要的,例如,如果你想在 char const*
上进行模板化,它必须是指向 char
具有外部链接。
#include <iostream>
// Compile with "-D LINKAGE=static" to see problem with "static"
#ifndef LINKAGE
# define LINKAGE extern
#endif
template< char const* s >
void foo()
{
std::cout << s << std::endl;
}
namespace {
LINKAGE char const message[] = "Hello, world!";
} // namespace anon
int main()
{
foo<message>();
}
也就是说,static
也没有被函数弃用,这有点不一致。
关于c++ - 未命名的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213282/