Unnamed/anonymous namespaces vs. static functions

后端 未结 11 1981
一个人的身影
一个人的身影 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:08

    Having learned of this feature only just now while reading your question, I can only speculate. This seems to provide several advantages over a file-level static variable:

    • Anonymous namespaces can be nested within one another, providing multiple levels of protection from which symbols can not escape.
    • Several anonymous namespaces could be placed in the same source file, creating in effect different static-level scopes within the same file.

    I'd be interested in learning if anyone has used anonymous namespaces in real code.

提交回复
热议问题