未命名/匿名命名空间与静态函数 [英] Unnamed/anonymous namespaces vs. static functions

查看:47
本文介绍了未命名/匿名命名空间与静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 的一个特性是能够创建未命名(匿名)命名空间,如下所示:

A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:

namespace {
    int cannotAccessOutsideThisFile() { ... }
} // namespace

您会认为这样的功能没有用——因为您无法指定命名空间的名称,因此不可能从外部访问其中的任何内容.但是这些未命名的命名空间可以在创建它们的文件中访问,就好像您对它们有一个隐式的 using 子句一样.

You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them.

我的问题是,为什么或何时这比使用静态函数更可取?或者它们本质上是做完全相同事情的两种方式?

My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?

推荐答案

C++ 标准在第 7.3.1.1 节未命名命名空间,第 2 段中阅读:

static 关键字的使用是在声明对象时不推荐使用命名空间范围,未命名命名空间提供了一个更好的选择.

The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.

静态仅适用于对象、函数和匿名联合的名称,不适用于类型声明.

Static only applies to names of objects, functions, and anonymous unions, not to type declarations.

不赞成使用 static 关键字(影响翻译单元中变量声明的可见性)的决定已被撤销 (ref).在这种情况下,使用 static 或未命名的 namespace 本质上又回到了做完全相同事情的两种方式.如需更多讨论,请参阅this SO question.

The decision to deprecate this use of the static keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.

未命名的 namespace 仍然具有允许您定义翻译单元本地类型的优势.请参阅 SO 问题了解更多详情.

Unnamed namespace's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.

感谢 Mike Percy 让我注意到这一点.

Credit goes to Mike Percy for bringing this to my attention.

这篇关于未命名/匿名命名空间与静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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