Thursday, 3 August 2017

c++ - Static and anonymous namespace











Is this completely redundant, or may there be a reason to do this?



namespace {
static void f() {
...
}

}

Answer



It looks redundant to me -- either being declared static or being in an anonymous namespace means it has internal linkage.



§3.5/3:




A name having namespace scope (3.3.6) has internal linkage if it is the name of:
— a variable, function or function template that is explicitly declared static;





§3.5/4:




[...] An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. [...] A name having namespace scope that has not
been given internal linkage above has the same linkage as the enclosing namespace if it is the name of
— a variable; or
— a function; or




So, as it is right now, it has internal linkage because it's explicitly declared static. If it wasn't explicitly declared static, it would have internal linkage because it's declared inside an unnamed namespace. Same effect either way.




Note that here I'm replying specifically about a function -- there are a few obscure cases where there's a difference when you're dealing with the name of a type (e.g., class/struct/union), but I don't know of any such thing that applies in the case of a function.



As far as what internal linkage really means, that's one of those places the standard is actually quite direct and clear. It's probably best to quote the definitions of all three possibilities (§3.5/2):




  1. When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.

  2. When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.

  3. When a name has no linkage, the entity it denotes cannot be referred to by names from other scopes.




Note that the italics above match those in the standard, which is its way of saying that these sentences define what those phrases mean throughout the rest of the standard.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...