Unnamed/anonymous namespaces vs. static functions

后端 未结 11 1986
一个人的身影
一个人的身影 2020-11-22 03:27

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

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


        
11条回答
  •  不思量自难忘°
    2020-11-22 04:15

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

    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.

    Edit:

    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.

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

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

提交回复
热议问题