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

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

问题描述

C ++的一个常用功能是可以创建未命名(匿名)命名空间,如下所示:

A little-used 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段:

The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:


static关键字的使用是

命名空间范围中声明对象时不推荐使用,未命名命名空间
提供了一个更好的选择。

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

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

编辑

决定不再使用static关键字影响翻译单元中变量声明的可见性)已被撤消( ref < a>)。在这种情况下,使用静态或未命名的命名空间回到基本上两种方式做同样的事情。有关详情,请参阅 SO问题。

The decision to deprecate this use of the static keyword (affect 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.

未命名的命名空间仍然具有允许您定义翻译单元本地类型的优点。有关详情,请参阅 SO问题。

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

Credit to the Mike Percy 引起我的注意。

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

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

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