Why are anonymous namespaces not a sufficient replacement for namespace-static, according to the standards committee?

前端 未结 3 428
陌清茗
陌清茗 2020-12-07 12:31

According to this answer, namespace-scoped static variables were undeprecated in C++11. That is, they were deprecated in C++03, because anonymous namespaces were considered

3条回答
  •  有刺的猬
    2020-12-07 13:05

    The user-in-the-trenches answer would be that names in unnamed namespaces (the standard's term for anonymous namespaces) have external linkage and names declared static at namespace level have internal linkage.

    Internal linkage has two advantages, only one of which unnamed namespaces provide, too:

    1. They make names local to the translation-unit. I can define the same function fun differently in different translation units without violating the One-Definition-Rule. This property is shared by names in the unnamed namespace, by adorning them with a unique namespace name.

    2. They prevent the name from entering into the global symbol table. This is strictly an optimisation, but an important one in practice. This property is not shared by names in the unnamed namespace.

    So, in general, a program that uses static for its translation-unit-local namespace-level functions generates less work for the linker and might execute faster than the equivalent program using the unnamed namespace.

    That said, you need to use the unnamed namespace for types that you want to pass as template arguments, because template arguments must have external linkage.

    So I usually do the follwing: define free functions as static, but put types into the unnamed namespace.

提交回复
热议问题