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 better. But C++11 undeprecated them.
Why? N3296 lists the reasoning for this as:
The use of static in namespace scope should not be deprecated. Anonymous namespaces are not a sufficient replacement for the functionality.
This was apparently accepted by the committee. Why? What is it about anonymous namespaces that does not completely replace this functionality?
I would prefer answers that had some documentation or paper trail of a standards committee discussion.
1.1 Unnamed namespaces, paragraph 2: The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
readability-static-definition-in-anonymous-namespace Finds static function and variable definitions in anonymous namespace. In this case, static is redundant, because anonymous namespace limits the visibility of definitions to a single translation unit.
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
Unnamed Namespaces They are directly usable in the same program and are used for declaring unique identifiers.
This is a more in-depth explanation.
Although 7.3.1.1 [namespace.unnamed] states that the use of the static keyword for declaring variables in namespace scope is deprecated because the unnamed namespace provides a superior alternative, it is unlikely that the feature will be removed at any point in the foreseeable future, especially in light of C compatibility concerns. The Committee should consider removing the deprecation.
One issue I know is that anonymous namespaces can't specialize templates outside of the namespace block. This is why inline namespace
was introduced, although static
works too. Also, static
plays much nice with macros.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With