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

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.

Related

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

C++ namespace and static variables

I have a requirement where a (const) variable should be available throughout an entire cpp which consists of several classes. I have decided to use a namespace to solve the problem, but unsure about the following:
Do I need to define this variable as static?
Is it true that I can avoid making the variable static only if I go with an unnamed namespace?
You don't need to define the variable as static, or in an anonymous namespace. However, if you're not using this object outside of the file it's defined in, it's a good idea, to reduce namespace pollution and speed up links (by reducing how many symbols need to be considered by the linker).
If you declare a variable in an anonymous namespace, it will be effectively static. There's no need to actually make it static as well (although you can if you like). The advantage of anonymous namespaces is you can also define types (classes, structs, enums, typedefs) as well as static variables and functions.

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

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.

Is it okay to use the this pointer? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Is there any reason to use this->
When should this-> be used?
When should I make explicit use of the this pointer?
When working with pointers to classes, I like to add a this-> in front of variables in a class to make it clearer that the variable I'm talking about is in the current class, as opposed to temporary variables, etc. So my lines would be something like
if(this->thing > other->thing)
this->doFoo();
Instead of
if(thing > other->thing)
doFoo();
Is it okay to add the superfluous this, or would that degrade code readability?
Consistency consistency consistency.
I conisder the this-> prefix a valid coding style if you use it throughout your entire project everywhere a member is accessed.
I prefer using a signifying prefix for members, e.g. m_. I feel it is less cutter and less tag soup than the explicit this->:
(alpha-this->gamma > this->alpha-gamma)
vs.
(alpha-m_gamma > m_alpha-gamma)
(The dotNetties have labeled m_ outdated - I use it on small C# projects out of spite. but anyway, any other distinct prefix would do, too.)
I've seen it used often to help intellisense get in gear, or to specifically filter members - which is ok, though leaving it in for that reason is questionable, especially if not used consistently.
That depends on your coding style, however many people would use
_myVariable
m_myVariable
myVariable_
To differentiate member variables from the other.
But the most important thing is to just be consistent
This is a style question, so answers will be subjective. Similarly, a lot of people I've worked with like to prefix member variables with m_ to make it clear that it's a member. (m_foo would be like your this->foo.) Then I'm sure there are people who feel this is a crime against the universe. YMMV. Use what works for you and anyone you might be working with.
One advantage (or disadvantage, depending on who you ask) to this-> is that you can have a variable with the same name that can be both a member and something locally scoped like a parameter or local variable, eg.:
foo bar;
void f(foo bar)
{
this->bar = bar;
}
As already noted this is, mostly, a matter of style.
Personally I do not use it for the data-members (I use the m prefix alternative), however I do use it for functions:
for consistency with templated code, where this might be necessary to defer lookup
for clarity, in order to distinguish at a glance whether it's a method of the class (possibly a base class) or a free-standing function
I think that, since you definitely don't want to trudge through levels of base class when reading up some code, the this-> clarification makes it much easier for the reader. And it's only 6 more characters to type.
I like this pattern too, but I like it more in managed code where it's "this." - the arrow operator does feel a bit noisier, but still it makes it very clear when you're referring to instance-level stuff.
of course you can do it, besides, the compiler would add it for you.
Normally you use this notation, when your method arguments and the member variables have the same name. (to differentiate the method argument with the member variable)
Say for e.g,
void CMYClass::fun1(int sameName)
{
...
this->sameName = sameName;
}
Otherwise, it's just a matter of taste...

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.