unnamed namespace(未命名的命名空间)
问题描述
标准规定的具体含义是什么
What does it exactly mean when the Standard states
$7.3.1.1/2 -》静态的使用声明时不推荐使用关键字命名空间范围内的变量(参见附件 D);未命名的命名空间提供了一个更好的选择."
$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."
我已经提到了 这个,但它没有涵盖我正在寻找的内容为.
I have referred this but it does not cover what I am looking for.
有没有一个例子清楚地证明了优越性.
Is there an example where the superiority is clearly demonstrated.
注意:我知道未命名的命名空间如何使外部变量在翻译单元中可见,但对其他翻译单元隐藏它们.但这篇文章的重点是关于静态命名空间范围"的名称(例如全局静态变量)
NB: I know about how unnamed namespaces can make extern variables visible in the translation unit and yet hide them from other translation units. But the point of this post is about 'static namespace scope' names (e.g global static variables)
推荐答案
究竟是什么意思?
技术上已弃用意味着未来的标准可能会删除该功能.
What does it exactly mean?
Technically deprecated means that a future standard may remove the feature.
实际上这不会发生,因为需要支持旧代码.
In practice that isn't going to happen, because of the need to support old code.
所以在实践中它的意思是强烈劝阻".
So in practice it means, "strongly discouraged".
未命名的命名空间通常更好,因为您在该命名空间中的内容可以具有外部链接.
An unnamed namespace is generally superior because what you have in that namespace can have external linkage.
在 C++98 中,对于可以是模板参数的东西,外部链接是必需的,例如,如果你想在 char const* 上进行模板化,它必须是指向 char<的指针/code> 具有外部链接.
In C++98 external linkage is necessary for things that can be template parameters, e.g., if you want to templatize on a char const*, it must be pointer to char that has external linkage.
#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 也没有被函数弃用,这有点不一致.
That said, it's a bit inconsistent that static isn't also deprecated for functions.
这篇关于未命名的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未命名的命名空间
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
