Is using namespace in an anonymous namespace safe? - c++

In "using namespace" statement inside an anonymous namespace it was asked whether the following is legal
//file.cpp
//....
namespace
{
using namespace std;
}
int a(){
cout << "bla";
}
The answer was "It is". Further, using namespace directives are generally despised even if inserted in cpp files since the scope differences between header and implementation files are not rock solid since the introduction of unity builds (https://stackoverflow.com/a/6474774/484230).
My question:
Does the anonymous namespace save me from such problems or can the using
directive still propagate file borders?
In https://stackoverflow.com/a/2577890/484230 a similar approach was proposed. Does it work for anonymous namespaces as well and is it really safe?
Of course std is a bad example but e.g. using namespace boost::assign; would be quite handy in some cpp files.

There isn't any difference between putting it in an anonymous namespace and putting it outside one. Either one produces the same effect, which is bringing the entire std namespace into your file's top-level namespace. This isn't good and it should be avoided.
As for "propogating file borders", it wouldn't do that if you put it outside the anonymous namespace either. The only time it can infect other files is if it's in a file that's #included in other files, such as headers.

My question: Does the anonymous namespace save me from such problems or can the using directive still propagate file borders ?
The only way the directive could propagate file borders is if some other file had a #include "file.cpp" preprocessor directive. That is perfectly legal, too, but whoo-ey, that stinks. Including a source file as opposed to a header is very much against standard practice.
Just because something is legal does not mean that it is good.
Pretty much the same goes for using the using to bring some other namespace into the current one. using namespace <name>; is general deemed to be bad form even in a source file.

Related

is namespace std defined in multiple headers

I am trying to understand namespace std. I know what a namespace is. I want to know, is namespace std defined in multiple header files?
I have two sample codes here, and they both compile and run fine. One uses #include<string> and the other uses #include<iostream>. Both use "using namespace std". This tells me that std is defined in both headers, is that right? If so, then when I use both headers in the same code, how will the compiler know which std to use?
CODE 1:
#include <string>
using namespace std;
int main()
{
string test;
test = "hello";
return 0;
}
CODE 2:
#include <iostream>
using namespace std;
int main()
{
string test;
test = "hello";
return 0;
}
A namespace is open; that is, you can add names to it from several separate namespace declarations. For example:
namespace A {
int f();
}
namespace A {
int g();
}
All namespaces with the same name (and in the same scope) are unified to one, so the compiler doesn’t have to choose.
"this tells me that std is defined in both the headers. is that
right?"
The headers include parts of the standard library. Both, iostream and string belong to the standard library, and each of them provides a different set of commands that can be addressed with std::.
The insertion of using namespace resolves the scope, which means that the compiler searches for a function or a command within std::: if it is not found in an inner scope. Therefore, instead of, e.g., writing std::cout << "Hello world" << std::endl; you can simply write cout << "Hello world" << endl; (assuming that iostream is included). This shortens and simplifies the writing of the code, but it can also have disadvantages, which is why using namespace std is generally considered bad practice.
Some headers of the standard library are included indirectly when another header is included. This appears to be the case in your Code2, which compiles although #include<string> is missing.
One cannot rely on such indirect inclusions. More information on this topic can be found here:
Do I have to use #include <string> beside <iostream>?
I know what a namespace is.
Perhaps you do, perhaps not exactly. A namespace is a tool used to prevent naming conflicts. Everything belonging (directly) to a namespace is public, as public identifiers are the only ones that can conflict with code outside the namespace. Unlike a class, there is no encapsulation or data integrity concerns to address; such concerns are relegated to the classes within the namespace.
This open nature of namespaces means that, unlike class definitions, a namespace definition need not be complete. All you need is for (the teams working on) the pieces of the namespace to coordinate their naming schemes. This is why it is typically wrong to add something to someone else's namespace. Since you are not part of the coordination, you could inadvertently introduce a conflict, perhaps quietly introducing undefined behavior, no diagnostic required.
Syntactically, though, you can add to any namespace. This is a useful feature, since traditionally one creates a header file for each class, and namespaces often span more than one class. So it is often desired for a namespace to span multiple header files. How to use namespace across several files? Just use the same namespace name in each namespace definition. A namespace definition is not so much a "definition" as it is a "tour". It is more "this is part of the namespace" than "this is the namespace". The more tours/parts you see, the more complete your view.
On the subject of incomplete views of a namespace, see Can the definition of a namespace span multiple translation units? (Hopefully you guessed "yes".)
I want to know, is namespace std defined in multiple header files?
Yes. The C++ standard dictates dozens of header files that must exist, and implementations are allowed to break those into auxiliary headers. See cppreference.com for a list of the required headers; the ones listed before the "C compatibility headers" section collectively define the std namespace.

May I place "using namespace std" into my namespace, that in a header?

I am writing a small library. Declaration of my classes, functions and others, that uses standard library are in a header file. I know that putting "using namespace" into header is a bad practic. May I put my code in separate namespace and then put "using namespace" into it?
Like this:
// header.h
namespace My
{
using namespace std;
// declarations
}
Will it be good?
Don't do it!
Simply use fully qualified names or using declaration for specific symbols that you want to use.
With this, You will just end up importing the contents of entire std namespace in your namespace My and essentially the header file header.h. Basically, it is going to give you namespace pollution with lot of unused symbols and also increase the compilation time of every translation unit where you include this header.
You may do that but it is not a good idea because this can lead to ambiguious names.

c++ namespace best practice dilemma

I'm finding that what I've considered "best practice" for use namespace in c++ is hurting the readability of my code, and making me question how to use them well.
My program consists of a few different modules which are mostly built into libraries that the "main" application uses. Each library uses it's own namespace, and their namespaces are all "inside" a project namespace to help project against name conflicts with 3rd party code. So I end up with class names such as "myproject::logging::Logger" and "myproject::reporting::ReportType" (As made up examples).
So far so good. And in my .cpp files I have no problem. I use "using myproject::logging" at the top for example, and can cleanly refer to my Logging class. In the unlikely event of a conflict between two of my namespaces I can just explicitly say which one I want. This works well.
Header files are different though. It's considered bad practice to put using statements into header files as they will affect unrelated code that may not expect them. So I always fully qualify all the names in .hpp files. That was somewhat ugly but managable up to now so I've put up with it. But now I'm increasing using template code in my libraries which means that there is much more actual code in my .hpp files now. And having to fully qualify every name is making the code practically unreadable due to the length of type names.
I'm starting to feel that the benefits of namespaces and best practice for using them are beginning to be outweighed by the unreadablilty of the code I'm having to write. I'm starting to wonder if I would be better abandoning the use of namespaces to gain the benefit of more readable code and fixing any name conflicts if and when they appear.
An alternative is to use short, single layer namespaces so instead of "myproject::logging::Logger" I would merely have "log::Logger" which would help a lot but make the likelyhood of namespace conflicts much higher, and also have the namespaces convey less useful information.
As I've said, this only really affects code in .hpp files as I'm happily using "using namespace" in my implementation files to make this manageable, but it is becoming a problem as I look at my templated code in .hpp files now and think "eww...." which can't be good :P
Anyone got any practical advice?
Here's what I do.
In <mylibrary.h>:
namespace myproject {
namespace mylibrary
{
namespace impl
{
using namespace otherlibrary;
using namespace boost;
using namespace std;
using namespace whatever::floats::your::boat;
class myclass;
class myotherclass;
};
using impl::myclass;
using impl::myotherclass;
};
};
In the source:
#include <mylibrary.h>
using namespace myproject::mylibrary; //clean!
I have been in this situation before. It is often the case that a lot of template functions/classes in your headers are really "implementation", although by the nature of templates in C++ you are forced to put them in a header file. Thus, I just put everything in some "detail" or "implementation" namespace, where I can comfortably use "using namespace". At the end, I "drop" what people should use to the corresponding place. Like this:
namespace myproject { namespace somemodule {
namespace _implementation {
using namespace myproject::othermodule;
using namespace myproject::yetanothermodule;
template <...>
class some_internal_metafunction{
...
};
template <...>
class stuff_people_should_use_outside {
...
};
} // namespace implementation
using stuff_people_should_use_outside ;
}} // namespace myproject::somemodule
This approach might enlarge a bit the names on your compiler reports, though.
Alternatively, you can give up the modules namespaces. But it might not be a good idea for an extremely large project.
Personally? I'd get rid of the "myproject" part. What is the chance that your library will use the exact same namespace name as another and have a symbol defined with the same name as another?
Also, I would suggest shorter names for namespaces you expect to be used in headers.
My experience have been that it is much more convenient to have one namespace for all your code for the reasons you mentioned in your original post. This namespace protects your identifiers from clashing with identifiers from 3rd-party libraries. Your namespace is your dominion and it is easy to keep it name-conflict-free.
I use the following to get rid of enormous amounts of std:: in header file:
// mylibrary.h
namespace myproject {
namespace mylibrary {
namespace impl {
using namespace std;
namespace stripped_std {
// Here goes normal structure of your program:
// classes, nested namespaces etc.
class myclass;
namespace my_inner_namespace {
...
}
} // namespace stripped_std
} // namespace impl
using namespace impl::stripped_std;
} // namespace mylibrary
} namespace myproject
// Usage in .cpp file
#include <mylibrary.h>
using namespace myproject::mylibrary;
It is similar to what was suggested by n.m., but with a modification:
there is one more auxiliary namespace stripped_std.
The overall effect is that line using namespace myproject::mylibrary; allows you to refer to the inner namespace structure, and at the same time it does not bring namespace std into library user's scope.
It's a pity though that the following syntax
using namespace std {
...
}
is not valid in C++ at the time when this post is written.
If your project isn't very very very huge (I mean, very huge), using only myproject should be sufficent. If you really want to divide your project into parts, you can use more generalized namespaces. For example, if I was building a game engine, I would go for namespaces like MyEngine::Core, MyEngine::Renderer, MyEngine::Input, MyEngine::Sound etc.

C++ using for std and boost namespace best practice [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Do you prefer explicit namespaces or 'using' in C++?
I am a C# developer, but my friend is a C++ one. He has shown me the code which is filled with calls like std::for_each and boost::bind. I used in C# and thought that using directives would rock for readability of the code and generally faster development. It would be a pain in the neck to type any namespace before C# foreach statement for example.
What are the cons and pros of using for such popular namespaces I am wondering?
Is it a best practice to include those namespaces or not?
First of all, let's make two distinctions:
1) There are using directives like using namespace std; and using declarations like using std::cout;
2) You can put using directives and declarations in either a header (.h) or an implementation file (.cpp)
Furthermore, using directives and declarations bring names into the namespace in which they're written, i.e.
namespace blah
{
using namespace std; // doesn't pollute the *global* namespace, only blah
}
Now, in terms of best practice, it's clear that putting using directives and declarations in a header file in the global namespace is a horrible no-no. People will hate you for it, because any file that includes that header will have its global namespace polluted.
Putting using directives and declarations in implementation files is somewhat more acceptable, although it may or may not make the code less clear. In general, you should prefer using declarations to using directives in such instances. My own preference is to always specify the namespace, unless it's annoyingly long (then I might be tempted).
In a header, if typing the namespace every single time is getting really tedious, you can always introduce a "local" namespace, e.g.
namespace MyLocalName
{
using namespace boost;
class X
{
// can use things from boost:: here without qualification
};
}
using MyLocalName::X; // brings X back into the global namespace
But never put using namespace boost; or the equivalent somewhere where it will drag all the stuff from Boost into the global namespace itself for other people.
I am against the using namespace statements, except maybe locally in a function's body. It's not a pain at all to write the full-qualified namespace before every identifier, except if you're writing like 500 loc per day.

How to use a single namespace across files?

I have a C++ project (VC++ 2008) that only uses the std namespace in many of the source files, but I can't find the "right" place to put "using namespace std;".
If I put it in main.cpp, it doesn't seem to spread to my other source files. I had it working when I put this in a header file, but I've since been told that's bad. If I put it in all of my .cpp files, the compiler doesn't recognize the std namespace.
How should this be done?
You generally have three accepted options:
Scope usage (std::Something)
Put using at the top of a source file
Put using in a common header file
I think the most commonly accepted best practice is to use #1 - show exactly where the method is coming from.
In some instances a file is so completely dependent on pulling stuff in from a namespace that it's more readable to put a using namespace at the top of the source file. While it's easy to do this due to being lazy, try not to succumb to this temptation. At least by having it inside the specific source files it's visible to someone maintaining the code.
The third instance is generally poor practice. It can lead to problems if you're dependent on more than one external source file both of which may define the same method. Also, for someone maintaining your code it obfuscates where certain declarations are coming from. This should be avoided.
Summary:
Prefer to use scoped instances (std::Something) unless the excessive use of these decreases the legibility and maintainability of your code.
In your headers, the best thing I think is just to fully qualify the namespace, say of a member
#include <list>
class CYourClass
{
std::list<int> myListOfInts;
...
};
You can continue to fully qualify in any function in a cpp
int CYourClass::foo()
{
std::list<int>::iterator iter = myListOfInts.begin();
...
}
you really never need "using namespace std" anywhere. Only if you find you are typing std:: too much, thats when its good to throw in a "using namespace std" to save your own keystrokes and improve the readability of your code. This will be limited to the scope of the statement.
int CYourClass::foo()
{
using namespace std;
list<int>::iterator iter = myListOfInts.begin();
...
}
You can put it in multiple places - in each .cpp file.
Essentially, you need to make a choice:
1) "do the right thing" by including using namespace std in all your cpp files, or
2) add using namespace std in some common header file.
Different people will have different opinions of which is best, however if you ask me, I'd chose to put using namespace std in a common header. In my opinion, the std namespace is just that - "standard" and any name conflicts need to be resolved at code level, rather than relying on namespaces.
The namespace doesn't 'spread' to other files.
You have to put it in each of the files, or just explicitly call out your classes.
either:
using namespace std;
blah << x;
or:
std::blah << x;
The choice is a style choice, either works in practice.
If the compiler doesn't 'recognize' the namespace it's because you haven't included the definition file that declares it ( i.e. include )
It's not a good idea to spread over your code using namespace std;only because it's seem convenient to you to do so. But if you insist on it you can wrap your own code into that name space. And only later when you will actually will make a use of your function/classes in the main file you will define using namespace std;. Just to emphasize that I'm saying, here the example:
namespace std
{
class MyNewClass
{
public:
MyNewClass( ) { out << "Hello there" << endl;};
};
};
int main( )
{
std::MyNewClass tmp;
};