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

前端 未结 3 445
陌清茗
陌清茗 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 12:58

    With unnamed namespaces you cannot give a variable internal linkage within the same namespace you are currently in. With static, you can. For example, the following use of unnamed namespaces does not give a global variable internal linkage

    namespace { int a; } 
    int a; // oops, no error!
    

    Had the first a been declared as static, the attempt to declare a second a at global scope would have been an error immediately because the first a already exists at global scope.

    So to achieve their job of making identity unique, unnamed namespaces place entities into different namespaces (in addition to affecting their linkage). static only affects the linkage, leaving the namespace of which functions and variables are a member of unchanged.

提交回复
热议问题