By akbiggs


2009-09-21 03:08:23 8 Comments

I've been told by others that writing using namespace std; in code is wrong, and that I should use std::cout and std::cin directly instead.

Why is using namespace std; considered a bad practice? Is it inefficient or does it risk declaring ambiguous variables (variables that share the same name as a function in std namespace)? Does it impact performance?

30 comments

@Kevin 2016-09-02 20:06:17

A concrete example to clarify the concern. Imagine you have a situation where you have two libraries, foo and bar, each with their own namespace:

namespace foo {
    void a(float) { /* Does something */ }
}

namespace bar {
    ...
}

Now let's say you use foo and bar together in your own program as follows:

using namespace foo;
using namespace bar;

void main() {
    a(42);
}

At this point everything is fine. When you run your program it 'Does something'. But later you update bar and let's say it has changed to be like:

namespace bar {
    void a(float) { /* Does something completely different */ }
}

At this point you'll get a compiler error:

using namespace foo;
using namespace bar;

void main() {
    a(42);  // error: call to 'a' is ambiguous, should be foo::a(42)
}

So you'll need to do some maintenance to clarify that 'a' meant foo::a. That's undesirable, but fortunately it is pretty easy (just add foo:: in front of all calls to a that the compiler marks as ambiguous).

But imagine an alternative scenario where bar changed instead to look like this instead:

namespace bar {
    void a(int) { /* Does something completely different */ }
}

At this point your call to a(42) suddenly binds to bar::a instead of foo::a and instead of doing 'something' it does 'something completely different'. No compiler warning or anything. Your program just silently starts doing something complete different than before.

When you use a namespace you're risking a scenario like this, which is why people are uncomfortable using namespaces. The more things in a namespace, the greater the risk of conflict, so people might be even more uncomfortable using namespace std (due to the number of things in that namespace) than other namespaces.

Ultimately this is a trade-off between writability vs. reliability/maintainability. Readability may factor in also, but I could see arguments for that going either way. Normally I would say reliability and maintainability are more important, but in this case you'll constantly pay the writability cost for an fairly rare reliability/maintainability impact. The 'best' trade-off will determine on your project and your priorities.

@Swiss Frank 2019-05-22 22:05:56

It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.

People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.

You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std symbol names for other purposes.

Given the number of classes, variables, and functions, stating std:: on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.

I'd offer the following rules:

  1. std is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std even if there isn't for other libraries.

  2. Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std everywhere may fine a few modules that are best handled as exceptions to that rule.

  3. Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo and std introduces a class named foo, it's probably better long-run to rename your class anyway.

  4. An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo() is instead AKFoo(). It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!)

One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using/namespace system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win, all signal-processing modules Mod, and so on.

There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.

@CryogenicNeo 2018-04-23 17:15:38

It doesn't make your software or project performance worse. The inclusion of the namespace at the beginning of your source code isn't bad. The inclusion of the using namespace std instruction varies according to your needs and the way you are developing the software or project.

The namespace std contains the C++ standard functions and variables. This namespace is useful when you often would use the C++ standard functions.

As is mentioned in this page:

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.

And see this opinion:

There is no problem using "using namespace std" in your source file when you make heavy use of the namespace and know for sure that nothing will collide.

Some people had said that is a bad practice to include the using namespace std in your source files because you're invoking from that namespace all the functions and variables. When you would like to define a new function with the same name as another function contained in the namespace std you would overload the function and it could produce problems due to compile or execute. It will not compile or executing as you expect.

As is mentioned in this page:

Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program. Let us take a few examples to understand why this might not be such a good thing

...

Now at a later stage of development, we wish to use another version of cout that is custom implemented in some library called “foo” (for example)

...

Notice how there is an ambiguity, to which library does cout point to? The compiler may detect this and not compile the program. In the worst case, the program may still compile but call the wrong function, since we never specified to which namespace the identifier belonged.

@Timon Paßlick 2017-10-30 21:52:30

To be honest, for me, that's like discussing the number of spaces for indentation.

Using directives in headers cause damage. But in C++ files? Maybe if you use two namespaces at once. But if you use one, it's more about style than real efficiency.

Do you know why threads about indentation are so popular? Anyone can say something about it and sound very smart and experienced.

@Engine Dev 2016-08-20 22:55:04

From my experiences, if you have multiple libraries that uses say, cout, but for a different purpose you may use the wrong cout.

For example, if I type in, using namespace std; and using namespace otherlib; and type just cout (which happens to be in both), rather than std::cout (or 'otherlib::cout'), you might use the wrong one, and get errors. It's much more effective and efficient to use std::cout.

@Martin G 2016-08-15 08:00:02

Here is an example showing how using namespace std; can lead to name clash problems:

Unable to define a global variable in C++

In the example a very generic algorithm name (std::count) name clashes with a very reasonable variable name (count).

@Rohan Singh 2015-04-05 12:56:24

A namespace is a named scope. Namespaces are used to group related declarations and to keep separate items separate. For example, two separately developed libraries may use the same name to refer to different items, but a user can still use both:

namespace Mylib{
    template<class T> class Stack{ /* ... */ };
    // ...
}

namespace Yourlib{
    class Stack{ /* ... */ };
    // ...
}

void f(int max) {
    Mylib::Stack<int> s1(max); // Use my stack
    Yourlib::Stack    s2(max); // Use your stack
    // ...
}

Repeating a namespace name can be a distraction for both readers and writers. Consequently, it is possible to state that names from a particular namespace are available without explicit qualification. For example:

void f(int max) {
    using namespace Mylib; // Make names from Mylib accessible
    Stack<int> s1(max); // Use my stack
    Yourlib::Stack s2(max); // Use your stack
    // ...
}

Namespaces provide a powerful tool for the management of different libraries and of different versions of code. In particular, they offer the programmer alternatives of how explicit to make a reference to a nonlocal name.

Source: An Overview of the C++ Programming Language by Bjarne Stroustrup

@nyholku 2015-06-11 12:48:27

Very interesting that a this answer that is based on guidance from no other that Bjarne Stroustrup has earned -2... boy Bjarne must have been a poor and inexperienced programmer when he introduced this feature into C++

@sbi 2015-08-04 16:01:52

@nyholku: See this.

@Carl 2015-02-12 00:40:14

I agree with the others here, but I would like to address the concerns regarding readability - you can avoid all of that by simply using typedefs at the top of your file, function or class declaration.

I usually use it in my class declaration as methods in a class tend to deal with similar data types (the members) and a typedef is an opportunity to assign a name that is meaningful in the context of the class. This actually aids readability in the definitions of the class methods.

// Header
class File
{
   typedef std::vector<std::string> Lines;
   Lines ReadLines();
}

and in the implementation:

// .cpp
Lines File::ReadLines()
{
    Lines lines;
    // Get them...
    return lines;
}

as opposed to:

// .cpp
vector<string> File::ReadLines()
{
    vector<string> lines;
    // Get them...
    return lines;
}

or:

// .cpp
std::vector<std::string> File::ReadLines()
{
    std::vector<std::string> lines;
    // Get them...
    return lines;
}

@Eyal Solnik 2016-03-11 09:23:35

Just a minor comment, while typedef is useful I'd consider making a class that represents Lines instead of using typedef.

@Nithin 2014-12-31 08:00:36

An example where using namespace std throws a compilation error because of the ambiguity of count, which is also a function in algorithm library.

#include <iostream>

using namespace std;

int count = 1;
int main() {
    cout << count << endl;
}

@PSkocik 2015-07-11 19:12:46

::count--problem solved. Usually you'll have more stuff from the std namespaced than from elsewhere, ergo keeping the using namespace directive might save you typing.

@Aiken Drum 2017-08-23 14:27:34

The real problem here is that C++ still has namespace-less globals. This, and the fact that 'this' is implicit in methods, causes so many bugs and problems I can't even count them, even with the right 'count' variable. ;)

@mattnewport 2014-11-03 20:00:25

Short version: don't use global using declarations or directives in header files. Feel free to use them in implementation files. Here's what Herb Sutter and Andrei Alexandrescu have to say about this issue in C++ Coding Standards (bolding for emphasis is mine):

Summary

Namespace usings are for your convenience, not for you to inflict on others: Never write a using declaration or a using directive before an #include directive.

Corollary: In header files, don’t write namespace-level using directives or using declarations; instead, explicitly namespace-qualify all names. (The second rule follows from the first, because headers can never know what other header #includes might appear after them.)

Discussion

In short: You can and should use namespace using declarations and directives liberally in your implementation files after #include directives and feel good about it. Despite repeated assertions to the contrary, namespace using declarations and directives are not evil and they do not defeat the purpose of namespaces. Rather, they are what make namespaces usable.

@dgnuff 2016-02-23 23:51:55

Just one more programmer's opinion here, but while I agree 100% with the statement that the word using should never appear in a header, I'm not as convinced about the free license to place using namespace xyz; anywhere in your code, especially if xyz is std. I use the using std::vector; form, since that only pulls a single element from the namespace into pseudo-global scope, therefore leading to far less risk of a collision.

@nyholku 2016-06-20 13:36:29

@Lightness Races in Orbit you are of course entitled to your opinion. Would have been more helpful if there had been some attempt at explanation why you do not agree with advice given in this answer. Especially would be interesting to understand what is the point of namespaces if 'using' them is bad? Why not just name things std_cout instead of std::cout ... the creators of C++/namespace must have had some idea when they bothered to create them.

@Lightness Races in Orbit 2016-06-20 14:03:31

@nyholku: No need - the majority of the other answers give the same reasons I would. Also please do no hesitate to note the ":)" I appended to my comment! And that I didn't say namespaces are bad.

@nyholku 2016-06-20 16:54:40

Yeah, I noticed that :) but IMO the majority of answer (that go against this sage advice) are misguided (not that I made any statistics what is the majority now). If you agree that namespace are 'not bad' then you might say where you think they are appropriate if you disagree with this answer?

@user4138451 2014-10-13 17:30:54

I agree with others – it is asking for name clashes, ambiguities and then the fact is it is less explicit. While I can see the use of using, my personal preference is to limit it. I would also strongly consider what some others pointed out:

If you want to find a function name that might be a fairly common name, but you only want to find it in the std namespace (or the reverse – you want to change all calls that are not in namespace std, namespace X, ...), then how do you propose to do this?

You could write a program to do it, but wouldn't it be better to spend time working on your project itself rather than writing a program to maintain your project?

Personally, I actually don't mind the std:: prefix. I like the look more than not having it. I don't know if that is because it is explicit and says to me "this isn't my code... I am using the standard library" or if it is something else, but I think it looks nicer. This might be odd given that I only recently got into C++ (used and still do C and other languages for much longer and C is my favourite language of all time, right above assembly).

There is one other thing although it is somewhat related to the above and what others point out. While this might be bad practise, I sometimes reserve std::name for the standard library version and name for program-specific implementation. Yes, indeed this could bite you and bite you hard, but it all comes down to that I started this project from scratch, and I'm the only programmer for it. Example: I overload std::string and call it string. I have helpful additions. I did it in part because of my C and Unix (+ Linux) tendency towards lower-case names.

Besides that, you can have namespace aliases. Here is an example of where it is useful that might not have been referred to. I use the C++11 standard and specifically with libstdc++. Well, it doesn't have complete std::regex support. Sure, it compiles, but it throws an exception along the lines of it being an error on the programmer's end. But it is lack of implementation.

So here's how I solved it. Install Boost's regex, and link it in. Then, I do the following so that when libstdc++ has it implemented entirely, I need only remove this block and the code remains the same:

namespace std
{
    using boost::regex;
    using boost::regex_error;
    using boost::regex_replace;
    using boost::regex_search;
    using boost::regex_match;
    using boost::smatch;
    namespace regex_constants = boost::regex_constants;
}

I won't argue on whether that is a bad idea or not. I will however argue that it keeps it clean for my project and at the same time makes it specific: True, I have to use Boost, but I'm using it like the libstdc++ will eventually have it. Yes, starting your own project and starting with a standard (...) at the very beginning goes a very long way with helping maintenance, development and everything involved with the project!

Just to clarify something: I don't actually think it is a good idea to use a name of a class/whatever in the STL deliberately and more specifically in place of. The string is the exception (ignore the first, above, or second here, pun if you must) for me as I didn't like the idea of 'String'.

As it is, I am still very biased towards C and biased against C++. Sparing details, much of what I work on fits C more (but it was a good exercise and a good way to make myself a. learn another language and b. try not be less biased against object/classes/etc which is maybe better stated as less closed-minded, less arrogant, and more accepting.). But what is useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), and sort (same thing) to name two that would cause a name clash if I were to do using namespace std;, and so to that end I prefer being specific, in control and knowing that if I intend it to be the standard use then I will have to specify it. Put simply: no assuming allowed.

And as for making Boost's regex part of std. I do that for future integration and – again, I admit fully this is bias - I don't think it is as ugly as boost::regex:: .... Indeed, that is another thing for me. There are many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var arguments [though I admit variadic templates are very very useful!]). Even those that I do accept it was difficult, and I still have issues with them.

@tambre 2018-06-22 13:42:31

@meupul 2013-09-17 06:55:16

I think using locally or globally should depend on the application.

Because, when we use the library locally, sometimes the code is going to be a real mess. Readability is going to low.

So, we should use libraries locally only when there is a possibility for conflicts.

I am not a more experienced person. So, let me know if I am wrong.

@Oleksiy 2013-08-29 09:44:39

I agree that it should not be used globally, but it's not so evil to use locally, like in a namespace. Here's an example from "The C++ Programming Language":

namespace My_lib {

    using namespace His_lib; // Everything from His_lib
    using namespace Her_lib; // Everything from Her_lib

    using His_lib::String; // Resolve potential clash in favor of His_lib
    using Her_lib::Vector; // Resolve potential clash in favor of Her_lib

}

In this example, we resolved potential name clashes and ambiguities arising from their composition.

Names explicitly declared there (including names declared by using-declarations like His_lib::String) take priority over names made accessible in another scope by a using-directive (using namespace Her_lib).

@Solkar 2013-05-13 15:18:27

"Why is 'using namespace std;' considered a bad practice in C++?"

I put it the other way around: Why is typing five extra characters considered cumbersome by some?

Consider e.g. writing a piece of numerical software. Why would I even consider polluting my global namespace by cutting general "std::vector" down to "vector" when "vector" is one of the problem domain's most important concepts?

@Jeremy Friesner 2013-09-03 03:42:55

It's not just 5 extra chars; its 5 extra chars every time you reference any object type in the standard library. Which, if you're using the standard library very much, will be often. So it's more realistically thousands of extra chars in a decent sized program. Presumably the 'using' directive was added to the language so that it could be used...

@DaveWalley 2014-03-06 01:54:36

Its not 5 extra chars every time, it is 5 chars and probably a couple mouse clicks to pull down a menu and do a Find and Replace in the editor of your choice.

@oz1cz 2014-10-24 09:47:48

Readability. cout << hex << setw(4) << i << endl; is easier to read than std::cout << std::hex << std::setw(4) << i << std::endl;

@oz1cz 2014-10-24 10:41:19

And even worse: std::map<std::string,std::pair<std::string,std::string>> is horrible compared to map<string,pair<string,string>>.

@juzzlin 2016-01-19 12:04:17

It's a good practice is to typedef your STL containers anyway so std:: there really doesn't matter. And C++11 brought us the auto keyword which makes things even easier when e.g. using iterators.

@Aiken Drum 2017-08-23 14:35:28

Agree with @juzzlin--the best code these days barely shows types at all. You can make the compiler infer almost everything with 'auto'. Only headers really have much call to specify, since the code needed to infer the type is usually not present.

@robson3.14 2009-09-21 15:47:31

One shouldn't use the using directive at the global scope, especially in headers. However, there are situations where it is appropriate even in a header file:

template <typename FloatType> inline
FloatType compute_something(FloatType x)
{
    using namespace std; // No problem since scope is limited
    return exp(x) * (sin(x) - cos(x * 2) + sin(x * 3) - cos(x * 4));
}

This is better than explicit qualification (std::sin, std::cos...), because it is shorter and has the ability to work with user defined floating point types (via argument-dependent lookup (ADL)).

@Billy ONeal 2010-12-05 17:15:07

I'm sorry, but I strongly disagree with this.

@Zan Lynx 2011-06-24 23:42:32

@Billy: There is no other way to support calling userlib::cos(userlib::superint). Every feature has a use.

@Billy ONeal 2011-06-24 23:48:07

@Zan: Of course there is. using std::cos; , using std::sin, etc. The issue though is that any well designed userlib is going to have their sin and cos inside their own namespace as well, so this really doesn't help you. (Unless there's a using namespace userlib before this template and that's just as bad as using namespace std -- and the scope there is not limited.) Furthermore, the only function like this I ever see this happen to is swap, and in such cases I would recommend just creating a template specialization of std::swap and avoiding the whole problem.

@sbi 2012-05-26 06:38:33

@Billy: Sometimes you will have to overload swap (like when you need it for you your own container). But even then a local using declaration is much better than a using directive.

@Billy ONeal 2012-05-30 14:53:22

@sbi: I don't see why an overload is required when a template specialization does the same job and doesn't require the caller to remember to activate ADL. (By not qualifying swap)

@sbi 2012-05-30 14:56:46

@BillyONeal: template<typename T> void swap(MyContainer<T>&, MyContainer<T>&) (There's no function template partial specialization (FTPS), so sometimes you need to resort to overloading instead.

@j_random_hacker 2015-09-04 15:31:07

@BillyONeal: Your (7-times-upvoted!) comment is wrong -- the situation you describe is exactly what ADL was designed to cover. Briefly, if x has one or more "associated namespaces" (e.g. if it was defined in namespace userlib) then any function call that looks like cos(x) will additionally look in those namespaces -- without any using namespace userlib; beforehand being necessary. Zan Lynx is right (and C++ name lookup is byzantine...)

@Ferruccio 2016-05-10 22:18:23

Instead of using namespace std;, I would prefer using std::sin; using std::cos; using std::exp;. You get the same benefit without any of the risks of dumping std::* into a function.

@Yelonek 2009-09-21 09:34:19

I also consider it a bad practice. Why? Just one day I thought that the function of a namespace is to divide stuff, so I shouldn't spoil it with throwing everything into one global bag.

However, if I often use 'cout' and 'cin', I write: using std::cout; using std::cin; in the .cpp file (never in the header file as it propagates with #include). I think that no one sane will ever name a stream cout or cin. ;)

@sbi 2012-05-26 06:41:08

That's a local using declaration, a very different thing from a using directive.

@Dustin Getz 2009-09-21 04:04:55

  1. You need to be able to read code written by people who have different style and best practices opinions than you.

  2. If you're only using cout, nobody gets confused. But when you have lots of namespaces flying around and you see this class and you aren't exactly sure what it does, having the namespace explicit acts as a comment of sorts. You can see at first glance, "oh, this is a filesystem operation" or "that's doing network stuff".

@Ron Warholic 2009-09-21 03:19:09

Consider

// myHeader.h
#include <sstream>
using namespace std;


// someoneElses.cpp/h
#include "myHeader.h"

class stringstream {  // Uh oh
};

Note that this is a simple example. If you have files with 20 includes and other imports, you'll have a ton of dependencies to go through to figure out the problem. The worse thing about it is that you can get unrelated errors in other modules depending on the definitions that conflict.

It's not horrible, but you'll save yourself headaches by not using it in header files or the global namespace. It's probably all right to do it in very limited scopes, but I've never had a problem typing the extra five characters to clarify where my functions are coming from.

@Martin Beckett 2009-09-21 03:13:18

Another reason is surprise.

If I see cout << blah, instead of std::cout << blah I think: What is this cout? Is it the normal cout? Is it something special?

@Brent Rittenhouse 2018-03-05 22:43:25

Is this a joke? I genuinely can not tell. If not then I personally would assume it's the normal 'cout' unless you don't trust the code since otherwise that would be a BEYOND MAJOR code smell, IMO. ... And if you don't trust the code then why are you using it in the first place? Note that I'm not saying "TRUST EvERYThING!!" but this also seems a bit far fetched if you're, say, dealing with some well known library from GitHub or something.

@James Hollis 2018-04-05 20:20:38

@BrentRittenhouse cout is a bad example because everyone recognizes it. But imagine future in a financial app. Is it a contract to buy or sell something at a specified date? No it isn't. If the code said std::future you would not be so easily confused.

@Swift - Friday Pie 2018-04-24 18:49:58

@BrentRittenhouse maybe a little bad example, there are at least four different libraries that have cout. May be "is it standard library? libstdc++? stl? something else?" And no, not everyone knows std::cout, at least inherently, 6 of 7 new workers we receive don't. Because curricula of education doesn't use those in education. I have to chase away printfs. Or debugs() - from Qt.

@mckenzm 2019-07-29 05:07:19

Really? It's pretty much in the first example of the first chapter of sooo many books on C++, if anything it (with insertion operator usage) is the only C++ some new bods know.

@Martin Beckett 2019-07-30 22:48:07

@mckenzm I might put it in a book or lecture notes to reduce clutter, but not in code

@Greg Hewgill 2009-09-21 03:13:50

This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:

using namespace foo;
using namespace bar;

Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.

If you had used foo::Blah() and bar::Quux(), then the introduction of foo::Quux() would have been a non-event.

@paxdiablo 2009-09-21 03:18:02

I've always liked Python's "import big_honkin_name as bhn" so you can then just use "bhn.something" rather than "big_honkin_name.something"- really cuts down on the typing. Does C++ have something like that?

@AraK 2009-09-21 03:19:37

@Pax namespace io = boost::filesystem;

@MattyT 2009-09-21 13:44:57

I think it's overstating things to say it's "some effort to fix". You'll have no instances of the new foo::Quux so just disambiguate all your current uses with bar::Quux.

@erikkallen 2009-09-21 19:14:06

Would any sensible person create a library with types whose unqualified name collide with the std types?

@sbi 2009-09-22 12:39:59

@MattyT: Things can get much worse than "having to fix". (see my answer: stackoverflow.com/questions/1452721/1453605#1453605).

@sbi 2009-09-22 12:42:00

@erikkallen: That the std lib has taken hundreds (or even thousands) of names, many of which are very popular and common (error, list, sort), was, IIRC, an important reason for putting it into its own namespace.

@Tomas Andrle 2009-09-22 19:55:18

To replicate the python "import longlongnamespace as spc" behaviour you can simply use a #define. I don't see anything wrong with that.

@sbi 2009-09-25 08:28:23

@TomA: The problem with #define is that it doesn't restrict itself to namespaces, but tramples over the whole code base. A namespace alias is what you want.

@AshleysBrain 2010-10-28 15:29:23

For the record, a namespace alias is using namespace bhn = big_honkin_name; as opposed to #defines or a using statement within a new namespace.

@Justin 2010-12-07 03:18:11

Why is this more of a problem in C++ than it is in C#? As far as I can see C# has exactly the same potential problem, but nobody would ever dream of using (for example) Company.Product.Component.Foo instead of just Foo

@Billy ONeal 2011-06-25 00:29:22

@Kragen: C++'s namespaces are large, while C#'s a relatively granular. (For the record I prefer at least partially qualified names in C# too but that's a whole different topic...)

@Lee Louviere 2012-02-28 20:07:43

@erikkallen Maybe not, but suppose you want to port your C++03 program to C++11 and find out std added a few things.

@Christian Rau 2013-03-07 16:54:25

@erikkallen Of course you would, considering that it contains such nice and common names like vector, set, or transform and that noone should blindly use using namespace std, anyway. Of course naming your things my_complex_vector_type or perform_a_transformation or set_this_value out of mere fear of std names is rubbish and completely invalidates the purpose of namespaces anyway.

@itsols 2013-04-20 13:49:23

@AraK A little too ignorant here... What do you mean by boost::filesystem? Does using the io namesapce improve performance? Sorry if this sounds silly :)

@JACH 2013-05-28 16:27:00

@itsols. AraK is talking about namespace alias: link

@Kevin Chen 2014-01-09 06:34:03

@erikkallen Boost, a well known C++ library, has many things that collide with iostream.

@Shayan RC 2014-03-21 03:15:58

So, as long as you use only one using namespace and it's not in the header file, you should be fine??

@bames53 2014-03-31 16:40:32

@ShayanRC Unfortunately there are libraries that don't use namespaces, so even one using namespace can create problems. Of course if you use multiple libraries that don't use namespaces then you're S.O.L.

@immibis 2015-02-25 00:13:10

@erikkallen What if someone wrote a class called unordered_map back in 2000, before it was in the standard library?

@Alex G 2015-05-09 06:20:04

So...using a namespace alias has been agreed to be the best way to avoid writing the entire namespace? Also, @bill commented about using namespace std::cout and using namespace std::cin -- did anyone see any potential issue with this, or is it deemed safe? It seems to me like this would avoid the "conflicting namespaces" issue while still allowing me to write cout << some code or cin >> some code, and only reserving std:: calls to the lesser-used std namespace calls.

@Black 2015-06-30 08:49:01

But why would someone ever create a function which is called "cout" or "cin"`!? I think this is all nonsense, i will keep using namespace std; forever because i don't think that someone will create a function called "cout","cin" or other well known functions like these.

@Luc Touraille 2015-06-30 09:26:47

@EdwardBlack cout and cin may not be the best examples, but some names are much more common and can be used by various libraries to mean different things. For example, there is a std::vector, a boost::mpl::vector, a boost::numeric::ublas::vector, which are all very different but all deserve the name vector.

@Luc Touraille 2015-06-30 09:32:25

@EdwardBlack Other examples of common names used in the std are system, time, pair, map, min, merge... Are you saying that no one should ever use these names in their libraries?

@Black 2015-06-30 12:05:45

why would someone use "system" or "time"?

@Tony Delroy 2015-09-14 03:00:48

@EdwardBlack: say you get some long protocol document from a stock exchange, in which "system" identifies something about the exchange; if you don't use the same identifier, you complicate adoption of and comparison against pseudo-code in the document, use of the document's index to find related info, the common terminology with which you can talk to people at the exchange about data issues etc.. Of course, the same issue exists for keywords, but that's no reason not to match exactly when you can.

@Travis Hohl 2015-10-26 21:45:48

@MattyT I think you're right, assuming you're the only programmer on the project and you're aware of the conflict when you upgrade to Foo 2.0.

@Slipp D. Thompson 2016-01-10 10:33:37

-1: This answer explains a potential clean-up task that may be necessary in the future, but not why it's a bad idea. Ending up with namespace conflicts happens in other languages, too, and as long as the compiler gives you a clear heads-up, it's usually not a big deal.

@grisumbras 2016-02-14 14:25:12

Using qualified name of a function prevents ADL. So there could not be a definite "never use using" rule.

@IInspectable 2016-08-03 14:20:34

@SlippD.Thompson: This answer really outlines the best that can happen: The compiler no longer compiling your code. No harm done. Another answer by sbi adds, that a far worse scenario is, if the compiler continues to compile your code. But with changed semantics. It silently compiles code you never intended to write. Now that is bad.

@Slipp D. Thompson 2016-08-03 19:27:05

@IInspectable I added more info regarding this to a comment on sdi's answer. Historically, this was a problem. However, modern compilers emit warnings or errors in this situation. That is, no, the compiler doesn't silently compile, it very specifically errors “reference to 'string' is ambiguous”.

@usr 2016-08-15 17:13:19

Seems like a defensive practice against a very rare case that is easily fixed. Among all the things that cause bugs, std namespace collisions must rank very low. Defensive practices have a cost. It's not a no-brainer.

@DBedrenko 2016-09-30 11:46:06

@itsols The point is to do less typing, and making the code more readable.

@Pavel 2017-05-03 07:26:50

I wouldn't consider that to be a problem at all as you get compilation error and you can fix it. Real problem may happen when compiler starts to silently use wrong function. For example, if you used bar::Quux(unsigned int) and then foo::Quux(int) was added.

@Zimano 2017-05-03 07:31:00

I downvoted this answer because I am highly unconvinced that libraries actually name their functions the same as the ones from std. I will also keep using it. There is no effort to fix, only a rename would ever be necessary.

@StaceyGirl 2017-06-13 17:34:59

Highly unconvinced? Oh boy! You never heard of Boost, don't you? std::filesystem and boost::filesystem, std::error_code and boost::system::error_code, std::chrono, boost::chrono, std::mt19937 and boost::random::mt19937 and many many more

@greggo 2017-11-15 19:30:12

@Zimano - take a longer view. How do you know that new things won't get added to std as enhancements in the future, which conflict with code or libraries that you already have?

@Sitesh 2018-02-01 15:41:53

@paxdiablo : now alias are present which can do the same thing

@Nic Hartley 2018-07-19 16:33:13

@Ivan To be fair, that's a little backwards -- it's more like what greggo said, where they were in Boost first, then adopted into std because they were so useful.

@ChrisW 2009-09-21 03:22:31

The problem with putting using namespace in the header files of your classes is that it forces anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.

However, you may feel free to put a using statement in your (private) *.cpp files.


Beware that some people disagree with my saying "feel free" like this -- because although a using statement in a cpp file is better than in a header (because it doesn't affect people who include your header file), they think it's still not good (because depending on the code it could make the implementation of the class more difficult to maintain). This FAQ topic says,

The using-directive exists for legacy C++ code and to ease the transition to namespaces, but you probably shouldn’t use it on a regular basis, at least not in your new C++ code.

The FAQ suggests two alternatives:

  • A using-declaration:

    using std::cout; // a using-declaration lets you use cout without qualification
    cout << "Values:";
    
  • Just typing std::

    std::cout << "Values:";
    

@Alexander Poluektov 2011-03-29 08:10:29

Experienced programmers use whatever solves their problems and avoid whatever creates new problems, and they avoid header-file-level using-directives for this exact reason.

Experienced programmers also try to avoid full qualification of names inside their source files. A minor reason for this is that it's not elegant to write more code when less code is sufficient unless there are good reasons. A major reason for this is turning off argument-dependent lookup (ADL).

What are these good reasons? Sometimes programmers explicitly want to turn off ADL, other times they want to disambiguate.

So the following are OK:

  1. Function-level using-directives and using-declarations inside functions' implementations
  2. Source-file-level using-declarations inside source files
  3. (Sometimes) source-file-level using-directives

@sbi 2015-03-26 03:22:00

Define "elegance".

@gnasher729 2014-03-13 17:22:28

It's nice to see code and know what it does. If I see std::cout I know that's the cout stream of the std library. If I see cout then I don't know. It could be the cout stream of the std library. Or there could be an int cout = 0; ten lines higher in the same function. Or a static variable named cout in that file. It could be anything.

Now take a million line code base, which isn't particularly big, and you're searching for a bug, which means you know there is one line in this one million lines that doesn't do what it is supposed to do. cout << 1; could read a static int named cout, shift it to the left by one bit, and throw away the result. Looking for a bug, I'd have to check that. Can you see how I really really prefer to see std::cout?

It's one of these things that seem a really good idea if you are a teacher and never had to write and maintain any code for a living. I love seeing code where (1) I know what it does; and, (2) I'm confident that the person writing it knew what it does.

@nyholku 2015-06-11 12:43:12

How do you know "std::cout << 1" isn't reading a static int named cout in std namespace shifting it by one and throwing away result? Also how do you know what "<<" does ;) ??? ... seems like this answer is not good data point to avoid 'using'.

@Jeremy Friesner 2016-07-07 04:33:35

If someone has redefined std::cout to be an integer, then your problem isn't technical, but social -- someone has it in for you. (and you should probably also check all of the headers for things like #define true false, etc)

@Tien Do 2018-08-31 04:52:20

When I see cout I know it's std::cout, always. If I'm wrong, it's problem of person who wrote this code, not me :)

@sbi 2009-09-21 09:26:50

I agree with everything Greg wrote, but I'd like to add: It can even get worse than Greg said!

Library Foo 2.0 could introduce a function, Quux(), that is an unambiguously better match for some of your calls to Quux() than the bar::Quux() your code called for years. Then your code still compiles, but it silently calls the wrong function and does god-knows-what. That's about as bad as things can get.

Keep in mind that the std namespace has tons of identifiers, many of which are very common ones (think list, sort, string, iterator, etc.) which are very likely to appear in other code, too.

If you consider this unlikely: There was a question asked here on Stack Overflow where pretty much exactly this happened (wrong function called due to omitted std:: prefix) about half a year after I gave this answer. Here is another, more recent example of such a question. So this is a real problem.


Here's one more data point: Many, many years ago, I also used to find it annoying having to prefix everything from the standard library with std::. Then I worked in a project where it was decided at the start that both using directives and declarations are banned except for function scopes. Guess what? It took most of us very few weeks to get used to writing the prefix, and after a few more weeks most of us even agreed that it actually made the code more readable. There's a reason for that: Whether you like shorter or longer prose is subjective, but the prefixes objectively add clarity to the code. Not only the compiler, but you, too, find it easier to see which identifier is referred to.

In a decade, that project grew to have several million lines of code. Since these discussions come up again and again, I once was curious how often the (allowed) function-scope using actually was used in the project. I grep'd the sources for it and only found one or two dozen places where it was used. To me this indicates that, once tried, developers don't find std:: painful enough to employ using directives even once every 100 kLoC even where it was allowed to be used.


Bottom line: Explicitly prefixing everything doesn't do any harm, takes very little getting used to, and has objective advantages. In particular, it makes the code easier to interpret by the compiler and by human readers — and that should probably be the main goal when writing code.

@Lie Ryan 2010-10-28 15:13:41

It does significantly harm the density of code you can pack in a single line. You end up writing your code in a very long-winded way; which reduces readability. Personally, I think shorter (but not too short) code tends to be more readable (since there is less stuff to read, and less stuff to get distracted about).

@sbi 2010-10-28 16:49:03

@Lie: Whether you like short or long prose is a subjective preference. (I have met developers who actually liked long identifiers, even though it meant they had to split their lines for even the simplest function calls.) Whether you see exactly which identifier, OTOH, is referred to is an objective criterion. FWIW, I used to share your POV, was forced to taste the other side, and never looked back.

@Lie Ryan 2010-10-28 16:56:20

@sbi: While I do not disagree that for non-std:: identifiers, being able to see where a name comes from can improve readability. I think the std:: denotation is just superfluous. Despite being an objective criterion, it has superficial value since you should expect any competent C++ programmer to know C++ standard libraries; and you'd expect no sane programmers would deliberately clash names with a standard library names. Personally, I put using namespace std on all of my code; though I use other namespaces conservatively, depending on frequency of usage.

@Mike DeSimone 2010-10-28 17:31:00

Guess you missed out on the old days before C++ had a standard string class, and seemingly every library had their own. Tell you what: We'll keep writing our code with std::, and you can run our code through grep -v std:: | vim when you're browsing it. Or you can teach your editor that std:: is a keyword which is to be colored the same as the background color. Whatever works.

@sbi 2010-10-28 17:56:11

@Lie: "I think the std:: denotation is just superfluous." Your main argument against typing out full identifiers, that they add to identifier length, will hardly apply to std::. But even so, I disagree. See this problem why.

@Lie Ryan 2010-10-28 18:16:10

@sbi: They applies much more so to std:: because they're used extremely frequently, at least in my codes. std::cout, std::cin, and std::endl is especially the most obscene offender. For vector/iterators, I'd write typedefs. Otherwise you end up with std::vector<std::string>::iterator. The problem you mentioned, is because someone named a function with the same name as a standard library function; I think you'd agree your solution with using &*ii is ridiculous, but IMO changing distance to take const& is just slightly less ridiculous. Better solution would be just to rename distance().

@sbi 2010-10-28 18:36:10

@Lie: "The problem you mentioned, is because someone named a function with the same name as a standard library function" And that's exactly the problem! How do you propose to avoid that? In the std namespace are hundreds (if not thousands) of identifiers, among them very popular ones. There are so many, you simply can't avoid clashing with them. And that's why they are all in std. Add using namespace std to your files, and sooner or later you run into such problems.

@jalf 2010-10-28 18:39:13

I don't think std:: is harmful at all. It carries very important information (namely "whatever comes after is part of the standard library", and it is still a pretty short and compact prefix. Most of the time, it's no problem at all. Sometimes, you have a few lines of code where you need to refer to specific symbols in the std namespace a lot, and then a using statement in that particular scope solves the problem nicely. But in the general case, it's not noise, it conveys valuable information in addition to removing ambiguities.

@Lie Ryan 2010-10-28 19:03:51

@sbi, @jalf: It uglifies your code, and I'm not going to take "no" for that.

@RjOllos 2011-04-11 17:45:46

It seems like a reasonable compromise would be to import namespace std in source files, but not import anything else. That avoids prefixing those library symbols that are likely the most frequently called, and also prevents the possibility of a namespace clash.

@sbi 2011-04-11 20:23:18

@RjOllos: It's spelled using in C++. That aside: Yes, you could do all kinds of compromises, but my argument was that 1) you can still run into problems (stackoverflow.com/questions/2879555/2880136#2880136), 2) code is, objectively, more readable when more explicit (because it spells out exactly what it does), and 3) it's wholly unnecessary, because abbreviating things is just a habit you can shed. Heck, there's many people writing Java, and some even write code in languages like Ada which really is a talkative language. I try to not to have to type StringUtilities::. But std::?

@Mateen Ulhaq 2011-09-14 06:50:42

Whenever I see std::, I know it's going to be from std:: without having to think about it. If I see string or list or map by themselves, I wonder a bit.

@Thoughtful Dragon 2012-12-29 13:09:24

@LieRyan it's three characters. The benefit outweighs the cost like an elephant outweighs a fly.

@Christian Rau 2013-03-07 17:04:46

@LieRyan Then good luck writing a geometry library without ever naming something vector, transform or distance. And those are just examples of the many many very common names used in the standard library. Suggesting not to use them out of fear or a biased opinion of the namespace feature that is an integral part of C++ is rather counter-productive.

@MvG 2013-06-03 10:01:03

“Explicitly prefixing everything doesn't do any harm” except where it breaks argument-dependent lookup (ADL) for e.g. swap. See also here. In those cases, using std::swap is better than directly calling std::swap.

@sbi 2013-06-03 14:01:12

@MvG: Of course, as with any rules, there's exceptions. That doesn't change the fact that, generally, using namesapce std; is considered a bad practice.

@Thomas 2014-05-07 13:01:03

This sounds dumb: it has taken me until now to realize the significance of knowing exactly what is going on in your programs. My teacher has always said, "You don't need to know that" whenever asked a question concerning the behind-the-scenes 'stuff' - something that has always unsettled me. But, Greg's answer has completely justified my curiosity and need to know what's going on.

@DarkWanderer 2014-12-01 09:25:11

the prefixes objectively add clarity to the code that's a substitution of opinion for an "objective" thing. By that logic, boost::numeric::ublas::vector_range<boost::numeric::ublas::v‌​ector<...>,> is the most readable and clear thing out there. Also, the example: To me this indicates that, once tried, developers didn't find std:: painful enough to employ using directives even once every 100kLoC even where it was allowed to be used. is also pretty subjective. In other words, downvote.

@alexandroid 2015-02-18 19:38:11

Sounds like compiler warnings could help identify cases when there are better matches happening for functions with same names but different namespaces originally. This would take at least part of the problem away.

@sbi 2015-02-18 20:19:17

@alexandroid: How do you propose compilers find out that your call used to end up with a different overload last week? Because that's a very probable scenario.

@alexandroid 2015-02-18 20:24:32

Oh no, I mean much simpler check - just the fact that some function being called has an overload from a different namespace (regardless of whether args match or not). Since we are talking about the case when both of functions are visible at the same time... (it won't help if there is a complete switch of course, i.e. one "using namespace" was replaced by another).

@sbi 2015-02-18 20:53:37

@alex: But ADL calls functions in other namespaces all the time! Every time you add two std::string instances, for example. Or call any other operator that's defined in a different namespace.

@Brandin 2015-11-24 09:58:04

If it's really "no big deal" to write "std::" before every standard identifier, why did C++ introduce namespaces at all? They could have defined all the standard identifiers with a C-style prefix, with names such as std_string, std_cout, etc... to avoid name conflicts. The whole point of namespaces is that you can write "using" if you're going to make use of those symbols, but can still disambiguate if needed (with emphasis on if). Without using 'using', namespaces are no better than C-style identifier prefixes.

@sbi 2015-11-24 11:14:46

@Brandin: How would you make ADL work with prefixes instead of namespaces? How would you call swap() so that any user-provided version is picked up? How would you do std::placeholders with prefixes? (You did read my answer thoroughly before criticizing, right? So you read the part where I said "except for function scopes", didn't you?)

@MikeMB 2016-01-09 03:01:53

I agree with the general statement, that using namespace std; can be harmful, but I disagree with some of your arguments: First about your datapoint: Just because developers don't use using namespace std; in function scope doesn't mean, they wouldn't use it in file scope, if it were allowed there. If your functions are short, the "price-benefit-ratio" is much worse in the function scope case. Second about readability: You wrote in a comment that "code is, objectively, more readable when more explicit".

@MikeMB 2016-01-09 03:06:35

... I don't think it's that easy: Adding std:: everywhere pushes the relevant parts more apart, makes the code broder and - in some / many cases - doesn't add any relevant information. This actually makes it more difficult to read and it depends on the situation and the reader, which effect actually is stronger. You probably also don't add unnecessary parenthesis to a sequence of math operations, although it would be more explicit.

@sbi 2016-01-09 23:32:01

@Slipp D. Thompson 2016-01-10 10:37:35

Are there no compiler flags to warn/error when the same name is used in a file, and appears in multiple namespaces, regardless of specializations? This seems like something people who write compilers would account for.

@sbi 2016-01-13 19:04:06

@Slipp: No, there most likely aren't, and you'd be very surprised about their results if there were any. Having programmed in C++ before namespaces were thought up, I can assure you that there's dozens of identical identifiers in every non-trivial C++ project. Clashes were a real problem back then. That is, after all, why namespaces were invented. If compilers warned about this, then we'd be right back at square one, where we can't use the same identifiers in different parts of the code.

@Slipp D. Thompson 2016-01-15 13:36:13

@sbi That makes sense, but a compiler warning would only make sense for things that are currently clashing— identifiers in the root namespace, or in ones you're using, and only for identifiers you're actually using in a given source file (the warning would be on the usage, not the declaration) . When an unwanted clash appears, you'd know to kill one of the usings in that file and be explicit instead. Maybe the namespaces are far more bloated in C++'s libs, but beyond that I guess I don't see how this is different from namespaces in C# or Java.

@Franklin Yu 2016-01-22 05:54:14

@SlippD.Thompson In short, what we need is not "same identifier error", but simply a "clash warning". I guess we should just not rely on compilers to choose.

@Slipp D. Thompson 2016-01-22 06:05:17

@FranklinYu Right. I'd assume it's works like Clang's other redefinition warnings where it gives you a list of all instances it's clashing with. Especially handy if that's integrated nicely into your IDE (like Clang is with Xcode).

@Slipp D. Thompson 2016-01-22 19:15:35

@FranklinYu Turns out Clang does indeed do exactly this— it gives me a hard “reference to 'string' is ambiguous” error. Proof here: cl.ly/eruf This is using a somewhat dated version of Clang (Xcode 5.1.1's Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn)), so if you're using Clang it's highly likely that you're already benefiting from this protection. | Sorry sbi, I have to downvote this one now. Historically this was a big issue, sure. But AFAIC it isn't any more.

@Franklin Yu 2016-01-23 05:50:10

@SlippD.Thompson, I got another example for function clashes. We see that it does not complain on identical identifiers (or there would have been an error at line 11), not even when they are both imported into root namespace (or there would have been an error at line 18), because actually I can access both safely with explicit namespace as line 22 and 23 (although not suggested). | Hence @sbi, I don't like using namespace std; globally as well, but it would not lead to the claimed problem with a modern compiler, so sorry for my downvote.

@Aluan Haddad 2017-05-08 08:37:07

I really like to refer to things in the narrowest posslbe scope, just like declaring variables at the site of first use, so I have no need for top level using namespace ns; but I do find using std::cout; at the function level to be rather elegant.

@Matti Virkkunen 2017-06-23 16:45:35

I'm sure everybody gets the point, there is no need to shout.

@ColdSteel 2017-09-30 21:08:04

Morale of the story -> don't use std at all ;-).

@Hammerite 2019-08-24 15:32:17

This answer misrepresents the two linked SO questions when it purports them to be examples of cases where code worked for a time and ceased to work upon a change of library or C++ standard. As far as I can tell, both are cases where the code never worked as the author expected it to in the first case.

@sbi 2019-09-04 19:25:00

@Hammerite: Nope, this answer doesn't interpret the two linked questions in this way.

@Hammerite 2019-09-04 21:20:21

Yes, it does. It purports the first to be a case where "pretty much exactly this happened" and describes the second as "another, more recent example" of such a thing. It offers both as backup of the proposition that working code might be broken by library changes - the thesis of the first section of the answer. It is interpreting (indeed: misinterpreting) the two linked questions just as I have said.

@adn.911 2017-11-30 16:24:48

This is a bad practice, often known as global namespace pollution. Problems may occur when more than one namespace has the same function name with signature, then it will be ambiguous for the compiler to decide which one to call and this all can be avoided when you are specifying the namespace with your function call like std::cout . Hope this helps. :)

@towi 2013-01-18 09:34:10

Do not use it globally

It is considered "bad" only when used globally. Because:

  • You clutter the namespace you are programming in.
  • Readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz.
  • Whatever is true for other readers of your source code is even more true for the most frequent reader of it: yourself. Come back in a year or two and take a look...
  • If you only talk about using namespace std you might not be aware of all the stuff you grab -- and when you add another #include or move to a new C++ revision you might get name conflicts you were not aware of.

You may use it locally

Go ahead and use it locally (almost) freely. This, of course, prevents you from repetition of std:: -- and repetition is also bad.

An idiom for using it locally

In C++03 there was an idiom -- boilerplate code -- for implementing a swap function for your classes. It was suggested that you actually use a local using namespace std -- or at least using std::swap:

class Thing {
    int    value_;
    Child  child_;
public:
    // ...
    friend void swap(Thing &a, Thing &b);
};
void swap(Thing &a, Thing &b) {
    using namespace std;      // make `std::swap` available
    // swap all members
    swap(a.value_, b.value_); // `std::stwap(int, int)`
    swap(a.child_, b.child_); // `swap(Child&,Child&)` or `std::swap(...)`
}

This does the following magic:

  • The compiler will choose the std::swap for value_, i.e. void std::swap(int, int).
  • If you have an overload void swap(Child&, Child&) implemented the compiler will choose it.
  • If you do not have that overload the compiler will use void std::swap(Child&,Child&) and try its best swapping these.

With C++11 there is no reason to use this pattern any more. The implementation of std::swap was changed to find a potential overload and choose it.

@Christian Rau 2013-03-07 17:09:40

"The implementation of std::swap was changed to find a potential overload and choose it." - What? Are you sure about that? Though it is true that providing a custom swap in the first place isn't that much important in C++11 anymore, since the std::swap itself is more flexible (uses move semantics). But std::swap automatically chosing your own custom swap, that is absolutely new to me (and I don't really believe it).

@towi 2013-03-08 08:44:45

@ChristianRau I think so, yes. I read this on SO somewhere. We can always ask Howard, he should know. I am digging and digging now...

@towi 2013-03-08 08:52:21

@ChristianRau Cant find a definitive link right now (need to go back to work), but I got to n3490 and n1252

@Adrian McCarthy 2014-02-27 17:24:44

Even in the swap case, the clearer (and thankfully more common) idiom is to write using std::swap; rather than using namespace std;. The more specific idiom has fewer side effects and therefore makes the code more maintainable.

@towi 2014-02-28 10:19:46

@AdrianMcCarthy I understood that the using std::swap idiom is usable even when having to do with non-idiomatic code. But I agree, when you have 100% control over the source, better be specific.

@Jonathan Wakely 2015-07-16 10:59:56

The final sentence is wrong. In C++11 the Std Swap Two Step was officially blessed as the right way to call swap, and various other places in the standard were changed to say they call swap like that (N.B. as stated above, using std::swap is the right way, not using namespace std). But std::swap itself was emphatically not changed to find some other swap and use it. If std::swap gets called, then std::swap gets used.

@Lundin 2015-10-26 11:02:03

It might be wiser to just type using std::swap locally though, to reduce the local namespace while at the same time creating self-documenting code. You are rarely ever interested in the whole std namespace, so just out pick out the parts you are interested in.

@Gaurav Singh 2018-06-17 10:01:38

"Readers will have difficulty seeing where a particular identifier comes from, when you use many using namespace xyz ". Yes, just like compilers

@towi 2018-06-22 11:10:46

@G_S "Yes, just like compilers" Even more so, even when there are no name clashes. Human readers will have more difficulties.

@m_highlanderish 2017-06-07 11:00:25

Here's a point of view I haven't found in any of the other answers: use only one namespace. The main reason why namespaces are bad, according to most of the answers, is that you can have conflicting function names which can result in a total mess. However, this won't occur if you use only one namespace. Decide which library it is that you will use the most (maybe using namespace std;) and stick with it.

One can think of it as having an invisible library prefix - std::vector becomes just vector. This, in my opinion, is the best of both worlds: on one hand it reduces the amount of typing you have to do (as intended by namespaces) and on the other, it still requires you to use the prefixes for clarity and security. If there's a function or object without a namespace prefix - you know it's from the one namespace you declared.

Just remember that if you will decide to use one globally - don't use others locally. This comes back to the other answers that local namespaces are often more useful than global ones since they provide variety in convenience.

@user2645752 2013-11-09 15:09:57

Using many namespaces at the same time is obviously a recipe for disaster, but using JUST namespace std and only namespace std is not that big of a deal in my opinion because redefinition can only occur by your own code...

So just consider them functions as reserved names like "int" or "class" and that is it.

People should stop being so anal about it. Your teacher was right all along. Just use ONE namespace; that is the whole point of using namespaces the first place. You are not supposed to use more than one at the same time. Unless it is your own. So again, redefinition will not happen.

@Tom Swirly 2016-05-24 23:32:42

Creating collisions isn't that hard - short strings like min, end and less appear in the std:: namespace. But more, now that std:: has thousands of symbols in it, it's useful for the reader to know where a new symbol they might not know comes from.

@Aiken Drum 2017-08-23 14:22:13

The std namespace exists because people, either you, your colleagues, or people writing middleware you use, are not always wise about putting functions inside of namespaces. Thus you may import all of std:: and nothing else, while still invoking a collision between, say, std::min and someone else's legacy ::min() from before the time when it was in std.

@harris 2013-04-09 03:44:15

Yes, the namespace is important. Once in my project, I needed to import one var declaration into my source code, but when compiling it, it conflicted with another third-party library.

At the end, I had to work around around it by some other means and make the code less clear.

@David Thornley 2010-10-28 17:37:11

I recently ran into a complaint about Visual Studio 2010. It turned out that pretty much all the source files had these two lines:

using namespace std;
using namespace boost;

A lot of Boost features are going into the C++0x standard, and Visual Studio 2010 has a lot of C++0x features, so suddenly these programs were not compiling.

Therefore, avoiding using namespace X; is a form of future-proofing, a way of making sure a change to the libraries and/or header files in use is not going to break a program.

@einpoklum 2016-02-24 16:40:46

This. Boost and std have a lot of overlap - especially since C++11.

@Ferruccio 2018-04-10 13:45:28

I did that once and learned a lesson the hard way. Now I never use using outside of a function definition and rarely use using namespace at all.

Related Questions

Sponsored Content

16 Answered Questions

[SOLVED] Why can templates only be implemented in the header file?

22 Answered Questions

11 Answered Questions

[SOLVED] Should 'using' directives be inside or outside the namespace?

6 Answered Questions

10 Answered Questions

12 Answered Questions

[SOLVED] std::wstring VS std::string

4 Answered Questions

[SOLVED] Declaring variables inside loops, good practice or bad practice?

26 Answered Questions

[SOLVED] How do I declare a namespace in JavaScript?

6 Answered Questions

4 Answered Questions

[SOLVED] Why are namespaces considered bad practice in JavaScript?

Sponsored Content