Unnamed/anonymous namespaces vs. static functions

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

    Putting methods in an anonymous namespace prevents you from accidentally violating the One Definition Rule, allowing you to never worry about naming your helper methods the same as some other method you may link in.

    And, as pointed out by luke, anonymous namespaces are preferred by the standard over static members.

提交回复
热议问题