Why an unnamed namespace is a "superior" alternative to static? [duplicate] - c++

This question already has answers here:
Superiority of unnamed namespace over static?
(2 answers)
Closed 9 years ago.
The section $7.3.1.1/2 from the C++ Standard reads:
The use of the static keyword is
deprecated when declaring objects in a
namespace scope; the unnamed-namespace
provides a superior alternative.
I don't understand why an unnamed namespace is considered a superior alternative? What is the rationale? I've known for a long time as to what the standard says, but I've never seriously thought about it, even when I was replying to this question: Superiority of unnamed namespace over static?
Is it considered superior because it can be applied to user-defined types as well, as I described in my answer? Or is there some other reason as well, that I'm unaware of? I'm asking this, particularly because that is my reasoning in my answer, while the standard might have something else in mind.

As you've mentioned, namespace works for anything, not just for functions and objects.
As Greg has pointed out, static means too many things already.
Namespaces provide a uniform and consistent way of controlling visibility at the global scope. You don't have to use different tools for the same thing.
When using an anonymous namespace, the function/object name will get mangled properly, which allows you to see something like "(anonymous namespace)::xyz" in the symbol table after de-mangling, and not just "xyz" with static linkage.
As pointed out in the comments below, it isn't allowed to use static things as template arguments, while with anonymous namespaces it's fine.
More? Probably, but I can't think of anything else right now.

One reason may be that static already has too many meanings (I can count at least three). Since an anonymous namespace can encapsulate anything including types, it seems superior to the static solution.

There are two reasons I think:
static has two different meanings: at class scope, it means shared by the whole class while at file/function scope it affects the visibility/storage...
unnamed namespaces allow to declare new struct, class and typedef
One note though, the commitee backpedaled on this: static is no longer marked as deprecated in n3225.

Related

Why we need 'namespace scope' concept? - in C++

I learned that in namespace "name decoration(mangling)" takes place so that it can be differentiated from other same identifiers which is in different namespace.
Wiki: Name mangling
If then, Why "namespace scope" exists? I thought just 'name decoration' can solve all problem about name conflicting.
Because in C, the reason for name conflicting is eventually that "different entities have same identifier".
Name decoration can make names(identifiers) different from each other internally, so I think name decoration is what all we need.
Then, why C++ use 'namespace scope' concept? Just for to use unqualified name in namespace scope? I want to know if there is any reason.
Namespaces scope is very useful in programming for the following reasons:
Avoids name collisions between functions/classes, eg., Suppose you have two functions of same name but in different namespace scope (foo::func() and bar::func())
Can be used for managing similar functions inside it, eg., sin(), cos() and sqrt() function could be under namespace Math.
Avoids confusion between classes for an example suppose there's two classes named lexer, but in different namespace scope like json::lexer and xml::lexer. Now, it gives clear understanding to the programmer to choose between them according to their language i.e, xml or json.
An everyday example of namespace could be std, stands for standard, it contains every single functions and classes defined in the standard library, it also includes STL classes like std::vector, std::map and std::string.
NOTE: There's no concept of namespace scope in C.
Namespace scope is a concept in the programming language that the developer sees, allowing them to organise their code effectively and understand it better. Name mangling is something the compiler does under the hood in order to implement namespaces (including namespace scope) in a way the linker can understand. In normal circumstances the developer doesn't need to think about name mangling, although its useful to know how it works.

Scoping functions within namespace versus within class [duplicate]

This question already has answers here:
Namespace + functions versus static methods on a class
(9 answers)
Closed 3 years ago.
I've got a bunch of functions(func1(),func2(),...) in a header file to which I want to give some scope. I know of 2 implementations:
class bunchOfFunctions
{
public:
static void func1();
static void func2();
...
};
namespace bunchOfFunctions
{
void func1();
void func2();
...
};
In both the options, I can access the functions in the same way i.e. by bunchOfFunctions::func(). I prefer the namespace method(lesser typing), but I've seen the 1st method of implementation also at my workplace.
Which option is better? Is there any other option?
Apart from StroryTeller highlighted points,
Spread: A namespace can be spread into multiple files where as Class must be defined in a single place.
Readability and Understandability: Generally developers inherent understanding of what a Class is and what a namespace is.
"Better" depends on your definition for better. What qualities are you looking for in the scoping? There is no one size fits all answer here. But here are some properties of both approaches:
Necessity to qualify the function name.
With a class you must write bunchOfFunctions::func1() when
utilizing those functions. Meanwhile a namespace allows you to pull
a function in with a using declaration
using bunchOfFunctions::func1;
and use it unqualified in most scopes. If you wished you could even make all the members of the namespace available to unqualified name lookup with a using directive. Classes don't have an equivalent mechanic.
Aliasing.
There is no difference. To alias the class one writes
using BOF = bunchOfFunctions;
while aliasing the namespace is done with
namespace BOF = bunchOfFunctions;
Privacy.
A class can have private members. So you could put function declarations in there under a private access specifier and use them in public inline members. Namespaces have no such mechanism. Instead we rely on convention and put declarations under a "do not touch this" internal namespace, often called bunchOfFunctions::detail.
Argument dependent lookup.
C++ has a mechanism that allows it to find function declarations from an unqualified call, by examining the namespaces that contain the arguments to the call. For that to work, the function must be in an actual namespace. Static members of classes are not subject to such a lookup. So for any member types you may have, only a namespace will allow calls via ADL.
These four are off the top of my head. Judge your needs for yourself. As for "Is there any other option?", those are the only two ways you have to group such functions in C++ today. In C++20, we'll have modules! That will offer another level of grouping for code.
In addition the information given above I would add that going back to the standard definition of what a class and what a namespace is can help with decisions like this.
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).
While these may sound similar they are rather specific. So if your functions are related, but not necessarily to the same object I would think hard about whether to put them in a class; particularly if grouping these functions together in a class may violate the Single Responsibility Principle: https://en.wikipedia.org/wiki/Single_responsibility_principle

Is there a difference between "anonymous" and "unnamed" in c++ semantic?

I've seen many people regarding them as the same,like unnamed(anonymous) namespace definition
However,there actually seems to be some difference between them,like Are “anonymous structs” standard? And, really, what are they?
As far as I'm concerned,both of them have no name,it seems hard to me to distinguish them from the semantic.
For example,the lambda is a unnamed object of an unnamed class,can we just say lambda is a anonymous object of an anonymous class?

Why are anonymous namespaces preferred to static globals? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Superiority of unnamed namespace over static?
Why unnamed namespace is a“ superior” alternative to static?
I know know anonymous namespaces are "encouraged" over static globals which are more C like (and deprecated), etc etc, and I use them often myself. However, despite having read other posts and questions about this topic, I haven't really seen explicit reasons why an anonymous namespace is better than a set of simple static globals.
Is there a definite reason why I should stick to the former?
Static variables at namespace scope are no longer deprecated.
There's no particular reason to prefer one over the other. A minor reason to prefer an unnamed namespace is that you can declare anything inside it, while only functions and variables can be static. A minor reason to prefer static declarations is that you don't have extra braces loitering around the declaration. Use whichever feels more harmonious to you.
Historical note: before C++11, there was one reason to prefer a namespace: for some bizarre reason, pointers to static objects or functions could not be used as template arguments, while pointers to non-static ones could. C++11 removes this restriction, along with the equally odd restrictions preventing, for example, local types being template arguments.

Should every class have its own namespace?

Something that has been troubling me for a while:
The current wisdom is that types should be kept in a namespace that only
contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions.
Does this imply that all classes must have a namespace of their own? If
we assume that a class may be augmented in the future by the addition of
non-member functions, then it can never be safe to put two types in the
same namespace as either one of them may introduce non-member functions
that could interfere with the other.
The reason I ask is that namespaces are becoming cumbersome for me. I'm
writing a header-only library and I find myself using classes names such as
project::component::class_name::class_name. Their implementations call
helper functions but as these can't be in the same namespace they also have
to be fully qualified!
Edit:
Several answers have suggested that C++ namespaces are simply a mechanism for avoiding name clashes. This is not so. In C++ functions that take a parameter are resolved using Argument Dependent Lookup. This means that when the compiler tries to find a function definition that matches the function name it will look at every function in the same namespace(s) as the type(s) of its parameter(s) when finding candidates.
This can have unintended, unpleasant consequences as detailed in A Modest Proposal: Fixing ADL. Sutter and Alexandrescu's rule states never put a function in the same namespace as a class unless it is meant to be part of the interface of that class. I don't see how I can obey that rule unless I'm prepared to give every class its own namespace.
More suggestions very welcome!
No. I have never heard that convention. Usually each library has its own namespace, and if that library has multiple different modules (e.g. different logical units that differ in functionality), then those might have their own namespace, although one namespace per library is sufficient. Within the library or module namespace, you might use namespace detail or an anonymous namespace to store implementation details. Using one namespace per class is, IMHO, complete overkill. I would definitely shy away from that. At the same time, I would strongly to urge you to have at least one namespace for your library and put everything within that one namespace or a sub-namespace thereof to avoid name clashes with other libraries.
To make this more concrete, allow me to use the venerable Boost C++ Libraries as an example. All of the elements within boost reside in boost::. There are some modules within Boost, such as the interprocess library that have its own namespace such as boost::interprocess::, but for the most part, elements of boost (especially those used very frequently and across modules) simply reside in boost::. If you look within boost, it frequently uses boost::detail or boost::name_of_module::detail for storing implementation details for the given namespace. I suggest you model your namespaces in that way.
No, no and a thousand times no! Namespaces in C++ are not architectural or design elements. They are simply a mechanism for preventing name clashes. If in practice you don't have name clashes, you don't need namespaces.
To avoid ADL, you need only two namespaces: one with all your classes, and the other with all your loose functions. ADL is definitely not a good reason for every class to have its own namespace.
Now, if you want some functions to be found via ADL, you might want to make a namespace for that purpose. But it's still quite unlikely that you'd actually need a separate namespace per class to avoid ADL collisions.
Probably not. See Eric Lippert's post on the subject.
Couple things here:
Eric Lippert is a C# designer, but what he's saying about bad hierarchical design applies here.
A lot of what is being described in that article has to do with naming your class the same thing as a namespace in C#, but many of the same pitfalls apply to C++.
You can save on some of the typedef pain by using typedefs but that's of course only a band-aid.
It's quite an interesting paper, but then given the authors there was a good chance it would be. However, I note that the problem concerns mostly:
typedef, because they only introduce an alias and not a new type
templates
If I do:
namespace foo
{
class Bar;
void copy(const Bar&, Bar&, std::string);
}
And invoke it:
#include <algorithms>
#include "foo/bar.h"
int main(int argc, char* argv[])
{
Bar source; Bar dest;
std::string parameter;
copy(source, dest, parameter);
}
Then it should pick foo::copy. In fact it will consider both foo::copy and std::copy but foo::copy not being template will be given priority.