tags:

views:

617

answers:

9

Exact Duplicate: Do you prefer explicit namespaces or ‘using’ in C++?

Which of these is a preferred convention for using any namespace?

using namespace std;

or

using std::cin;
using std::cout;

or

calling the function as and when required in the code?

std::cout<<"Hello World!"<<std::endl;
A: 

Whatever you prefer. Really, it doesn't matter. However, most code-snippets use

using namespace std;
raphaelr
...and that defeats the whole purpose of namespacing.
missingfaktor
that's because most code snippets are small, and designed for maximum readability. Production code is designed for maximum robustness first, readability second. Pulling in an entire namespace will make writing code brittle, especially if you put it in a header file.
Steve
snippets != real code
rlbond
+10  A: 
anon
for small implementation files I don't see the problem with using namespace. I suppose if you had a gigantic class, you could run into problems.
Steve
What is "small"? I don't write gigantic classes, but I also don't keep every name in the C++ Standard Library in my head. Explicitly specifying the names I commonly use avoids nasty (and very, very difficult to debug) problems.
anon
Although ADL can work around your best plans to avoid polluting your context with the names of standard functions. `#include <vector> #include <algorithm> int main() { std::vector<int> foo; std::vector<int> bar; copy(foo.begin(), foo.end(), bar.begin()); }`. If you were planning to use the name "copy" for something else, best make sure you never accidentally call your version when meant an overload found by ADL, or vice-versa.
Steve Jessop
I like to add that the using (directive/statement) can be scoped. So try and be specific where you use it.
Martin York
@Martin York: But, Visual Studio 2008 seems to handle this incorrectly, and makes any using directive file scope.
rlbond
@rlbond: that is horrifying! Do they have any plans on fixing the defect? Elevating the scope of a `using` directive can be devastating.
D.Shawley
+2  A: 

It is a matter of style, but for one thing: You should never import a namespace into the global scope. e.g.:

#include <iostream>
using namespace std; // Pollution!

int main()
{
    ....
}

If you want to import the namespace just import it to the scope where you are working:

#include <iostream>

int main()
{
    using namespace std; // Good!
    ....
}
AraK
Not really. It depends on your program (how big it is, how much it makes use of the standard library, etc.).
Brian Neal
@Brian Do you mean that importing a namespace to the global scope is OK?!
AraK
I will say that it is ok. Not in a header file, but it's ok. It's bad to be dogmatic about these things, and in most cases it's not terrible. For example, if i'm going to use a graph library in a source file, it's all right to say `using namespace MyGraphLibrary;`. The world won't explode, your code will be ok. It's not pollution if you're careful about it.
rlbond
@AraK, not in a header file. But in a source file it is perfectly acceptable under the right circumstances.
Brian Neal
+14  A: 

A very good explanation is given here.

The first style i.e. using namespace whatever defeats the whole purpose of namespacing. You should never be using it except in small code snippets. (I don't use it there either! :D )

Second one is way too verbose. Not practical.

I personally like the third style i.e. typing out the fully qualified name (e.g. std::cout).

Remember, the code is read much more times than it is written & using fully qualified names IMO makes your code more readable.

missingfaktor
The purpose of any concept in programming is to make life easier for programmers. If you're making heavy use of the standard library, `using` something can make your code more concise. How is `using std::string; string a; string b; string c; string d` more verbose than `std::string a; std::string b; std::string c; std::string d;` ? If you have to use it a lot, the fully qualified name gets cumbersome. And seriously, who's going to be hand-rolling their own `string` class when there's already a `std::string` ? If you say `string x` 95% of the time it's `std::string` and everyone knows it.
Chris Lutz
That is one exception. What if you say "using std::count" and later need to define a function or variable with the same name?
missingfaktor
Disagree: I don't see any problem with `using namespace std;` in a source file. But NEVER use #1 or #2 in a header file.
rlbond
@rlbond : Well, I am of the opinion that whatever style you use, you should be consistent with that. That's why I always stick to the third style. Works with both headers and source files. And as you can see, it all comes to down to the matter of style. One size does not fits all!
missingfaktor
@Chris : This is from the Marshall Cline link I've posted in my original post : "I personally find it's faster to type "std::" than to decide, for each distinct std name, whether or not to include a using-declaration and if so, to find the best scope and add it there."
missingfaktor
In my opinion the first style does in no way defeat the purpose of namespaces. If there are ambiguities due to namespace collisions they can be resolved by specifying. Readability of code is paramount and the first style can genuinely assist.
MattyT
+7  A: 

This is a modified version of another answer I wrote on the same subject. Enough of these questions and maybe I will end up with a definitive post ;)

The major issue is name conflicts, in that if you have a variable called cout in your code and you are using namespace std; it will be ambiguous as to what you mean. It isn't just cout. count, reverse and equal will also be included, which are all common identifiers.

Disregarding all problems to the compiler, it is also a problem for anyone coming to read your code. Those extra 5 characters ensure that the next person maintaining your code knowns exactly what you mean.


It is also worth noting that you should never put

using namespace std;

In a header file, as it can propagate to all files that include that header file, even if they don't want to use that namespace. Another problem here is that it is also not clear that the std namespace has been imported, so the maintainer (or you in 3 months time) adds a variable with the same name as some obscure std function that was included into the same compilation unit and then spends an hour trying to find the cause of the compilation error.

In the majority of cases it is very beneficial to use things like

using std::swap

As if there is a specialized version of swap, the compiler will use that, otherwise it will fall back on std::swap. If you call std::swap, you always use the basic version, which will not call the specialized version (even if it exists).

Take for example code using the pimpl idiom. Where as the default copy may copy all the data in the actual implementation, where as all that needs doing is swapping the pointers. Using a specialized swap could save huge amounts of execution time, and well designed libraries should specialize it.


In summary,

  • Always prefer using std::swap over std::swap()

  • Avoid using namespace std in a header at all costs due to propagation, try to avoid using it in implementation files.

  • Having thousands of using std::foo at the top of every file is not the way to go. At most use it for commonly use classes.

Everything else is opinion.

Yacoby
+1: interesting thought on `std::swap` usage that I personally disagree with. However, after reading a USENET posting from 2000 (http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/b396fedad7dcdc81) on the subject, I am more interested in it. Personally, I favor the _use `std::swap` and specialize it_ camp.
D.Shawley
+3  A: 

I personally prefer the third option. Just have a look at this:

namespace A { int a=0; }
namespace B { int a=0; }

and you use it as:

using namespace A;
using namespace B;
using namespace std;

cout<<a<<endl; //error here!

Instead if you could just say,

std::cout<<B::a<<std::endl; //No problem, more readable

Although it might take a bit more time to type the code out, the second and the third options are more (kind of) preferred.

Srivatsan Iyer
None of those are more or less readable because you don't use any spaces around your symbols. Code snippets on SO can still look __nice__.
Chris Lutz
+1  A: 

I'd just like to point out that using namespace foo is scoped. Example:

#include <iostream>
#include <vector>
//...
for (int i=0; i<10; ++i)
{
    using namespace std;
    cout << i << endl;
}
vector v; // won't compile

When used with care, using namespace std can be useful and harmless at the same time.

sbk
+1  A: 

I always list out the full namespace. It improves readability and lets other people know where your functions and data are coming from. using is very annoying when reading other peoples' code, especially when I'm trying to learn something, because I can't tell if it's part of that namespace or the other. And like these other sensible people are saying, it does defeat the whole point of namespacing, doesn't it? The point is to keep everything separate and give meaning to the data and logic.

A good order to remember: the most important person is the client who uses the program; second most important is other coders who are either maintaining or trying to learn from your code; least important is you. :-)

alecRN
+1 for the last sentence! :)
missingfaktor
A: 

It's one thing to recommend writing out the fully qualified name when the namespace is std, where std:: only adds 5 extra characters. It's a whole 'nother issue when namespaces stack, and you are faced with writing something like:

if (NumberOfInstances > 0 && (code_type == MyNamespace::MyLongButMeaningfulClassName::EnumDefinedWithinClass::CODE_GREEN ||
                              code_type == MyNamespace::MyLongButMeaningfulClassName::EnumDefinedWithinClass::CODE_YELLOW)) {

especially if you have a company style guidline limiting lines to 80 characters and you add a few more indents. Something like that obscures the logic of the code behind all the verbiage. At that point, you start to appreciate using and/or local namespace aliases, in the interest of readability.

dewtell