Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.

like image 859
Nicol Bolas Avatar asked Dec 10 '11 22:12

Nicol Bolas


People also ask

Why is an unnamed namespace used instead of static?

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.

Is a static definition in anonymous namespace static is redundant here?

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.

What is the point of anonymous namespace?

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.

Why do we use unnamed namespace?

Unnamed Namespaces They are directly usable in the same program and are used for declaring unique identifiers.


1 Answers

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.

like image 72
Pubby Avatar answered Oct 21 '22 14:10

Pubby