Monday, 20 August 2018
c++ - Unnamed/anonymous namespaces vs. static functions
Answer
Answer
A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so:
namespace {
int cannotAccessOutsideThisFile() { ... }
} // namespace
You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them.
My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?
Answer
The C++ Standard reads in section 7.3.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.
Edit:
The decision to deprecate this use of the static keyword (affect visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.
Unnamed namespaces still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.
Credit goes to Mike Percy for bringing this to my attention.
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
No comments:
Post a Comment