未命名命名空间优于静态命名空间?

2023-12-03C/C++开发问题
4

本文介绍了未命名命名空间优于静态命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

未命名命名空间如何优于 static 关键字?

How are unnamed namespaces superior to the static keyword?

推荐答案

您基本上是指 C++03 标准中的 §7.3.1.1/2 部分,

You're basically referring to the section §7.3.1.1/2 from the C++03 Standard,

static 关键字的使用是在声明对象时不推荐使用命名空间范围;这未命名命名空间提供了一个优越的替代.

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 函数已按照标准 不再被弃用!

Note that this paragraph was already removed in C++11. static functions are per standard no longer deprecated!

尽管如此,未命名的 namespace 优于 static 关键字,主要是因为关键字 static 仅适用于 变量 声明和函数,而不是用户定义的类型.

Nonetheless, unnamed namespace's are superior to the static keyword, primarily because the keyword static applies only to the variables declarations and functions, not to the user-defined types.

以下代码在 C++ 中有效:

The following code is valid in 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,就是这样:

So the solution is, unnamed (aka anonymous) namespace, which is this:

//legal code
namespace 
{  
     class sample_class { /* class body */ };
     struct sample_struct { /* struct body */ };
}

希望它能解释为什么未命名的namespace优于static.

Hope it explains that why unnamed namespace is superior to static.

这篇关于未命名命名空间优于静态命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6