Unnamed/anonymous namespaces vs. static functions

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

    Personally I prefer static functions over nameless namespaces for the following reasons:

    • It's obvious and clear from function definition alone that it's private to the translation unit where it's compiled. With nameless namespace you might need to scroll and search to see if a function is in a namespace.

    • Functions in namespaces might be treated as extern by some (older) compilers. In VS2017 they are still extern. For this reason even if a function is in nameless namespace you might still want to mark them static.

    • Static functions behave very similar in C or C++, while nameless namespaces are obviously C++ only. nameless namespaces also add extra level in indentation and I don't like that :)

    So, I'm happy to see that use of static for functions isn't deprecated anymore.

提交回复
热议问题