Skip to main content
GameDev.net gamedev.net
🔒 Locked

Why use std:: ?

Started by Zodiak Apr 22, 2005 at 1:36 AM 18 replies 3.9k views
Original Post
Zodiak
Zodiak
Hello! I've been browsing these forums for a long time already (less than a month though) and noticed that 99% of programmers here use something like 'std::string, std::cout' etc. I can't understand why do you do that? Isn't it easier to just write 'using namespace std' at the top of the file and not bother anymore? I am sure you are not fools to program in such a way (hell no!) but the reason why you prefer to write 5 extra chars everytime you use something is beyond me. Thanks!
I'd definetly say that a glass is half-empty!
Roboguy
Roboguy
Some people considering using namespace bad practice: it pollutes the global namespace and, if it's in a header file, it forces the user of the header file to have everything that's in the namespace std in the global namespace.

For example, if you were using namespace std; you couldn't do:
std::string string;// etc...
Drew_Benton
Drew_Benton
In addition, there may be conflics with other libraries or code used. If you use the std:: form, you are explicitly telling the compiler what you want to use. Also, along the same lines, you may never know what's all defined in the namespace. A function could be called that might vary from what you are expecting and can lead to mixed results.

In principle in general it also is helpful to seeing what all you have to do in order to get something to work. I've been using Ogre recently and it is quite a large graphics engine. In all of the examples, they simply do a using namespace Ogre;. Yes while it cuts down on typing, you aren't learning all of what belongs to Ogre. By using Ogre::Vector3, you will easily learn that a lot faster from having to type it out rather than just using Vector3. Sounds kind of counter intuitive, but give it a try [wink]
simon10k
simon10k
Namespaces help prevent name clashes. Full stop. You could go as far to say they express modularity but that might confuse you.

I think Robo is also a bit confused about namespaces. :)

This is possible...
 #include <iostream>using namespace std;int main(){ 	std::cout << "hello, world\n";}

-----------------------------Language: C++API: Win32, DirectXCompiler: VC++ 2003
Jingo
Jingo
To understand why people use std:: requires you to understand reasons why namespaces are in the language in the first place.

Probably the most important reason is to prevent name clashes. Imagine for a second that namespaces did not exist. Now imagine that you were trying to implement a class to represent a vector. You would like to call this class vector.

//myvector.hpptemplate<typename T>class vector{T elements[3]; //3d};



All is well with the world until you decide that you need to use your new vector class and the vector class provided by the C++ standard library in the same program.

#include<myvector.hpp>#include<vector>int main(){vector<int> myvector; //which vector is this???}


Without the concept of namespaces there is no way to distinguish between these two classes.

The 'using namespace std;' expression often has the same effect of introducing ambiguity into the code. In fact you could almost say that 'using namespace' defeats the whole purpose of namespaces. Imagine now that you had used namespace.

#include<myvector.hpp>#include<vector>using namespace std;using namespace mynamespace; //myvector is in this namespace nowint main(){vector<int> myvector; //which vector is this??}


Again there is an ambiguity here, the using namespace expressions have had the same effect as using no namespaces at all.

For this reason, most people prefer to use the form

#include<myvector.hpp>#include<vector>int main(){std::vector<int> myvector; mynamespace::vector<int> myothervector;}


Endurion
Endurion
All that above, plus a minor feature but nonetheless important for lazy programmers:

Typing the :: will open up Intellisense :)
Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>
bobstevens
bobstevens
The usual advice is never to use "using namespace" in a header file. I think some people have twisted that advice around in their heads because they like typing a ton of annoying an unnecessary stuff.

Seriously... who would use "std::string string" anyway?
Cygon
Cygon
The actual advice should be: "Never use 'using namespace' globally in a header file".

If you've get a conflict like with the two vectors, you don't know which one is used, but that also counts for the compiler, it will report an "ambiguous symbol error", forcing you to write std:: or mylib:: in front of the ambiguous name being used to tell it which of the two conflicting names you actually mean.

Also, using namespace can safely be used in a header within the context of a method or function, like in this fictional example:
// My.h#include <iostream>inline void displayCopyrightMessage() {  using namespace std;  cout << "Copyright by xyz" << endl       << "dont copy around, bla bla" << endl;       << "legal consequences, bla bla" << endl;}


Sure, one might argue just 'using std::cout' and 'using std::endl' might be better for only two members of the std namespace ;)

-Markus-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
simon10k
simon10k
In a large project you have more than just the standard namespace to deal with. I think it is safer to just get use to using the namespace prefix.
-----------------------------Language: C++API: Win32, DirectXCompiler: VC++ 2003
DinGY
DinGY
i think we can use "using something;" instead of "using namespace std;"

example:
#include <iostream>#include <vector>#include <string>using std::cin;using std::cout;using std::vector;using std::string;
DinGY
Yesterday is history.Tomorrow is a mystery. Today is a gift"
Jingo
Jingo
Quote:
Original post by Cygon
The actual advice should be: "Never use 'using namespace' globally in a header file".

If you've get a conflict like with the two vectors, you don't know which one is used, but that also counts for the compiler, it will report an "ambiguous symbol error", forcing you to write std:: or mylib:: in front of the ambiguous name being used to tell it which of the two conflicting names you actually mean.

Also, using namespace can safely be used in a header within the context of a method or function, like in this fictional example:
*** Source Snippet Removed ***

Sure, one might argue just 'using std::cout' and 'using std::endl' might be better for only two members of the std namespace ;)

-Markus-


I can imagine the hell that would cause in a work enviroment where classes may often have the same name, and source files often exceed 100k lines of code. Having to search through the file to see which namespaces have been injected into the global namespace. O the fun.

Though in the amateur environment where you are the only person working on a project, and the project is small, using namespace std is not the greatest of all sins.
bobstevens
bobstevens
Quote:
Original post by Jingo
I can imagine the hell that would cause in a work enviroment where classes may often have the same name, and source files often exceed 100k lines of code. Having to search through the file to see which namespaces have been injected into the global namespace. O the fun.


If you're a person who prefers to prepend the namespace to everything, you'll never have to worry about what was injected into the global namespace since you'll never be using it. Right?

Ambiguities are easily resolved between multiple namespaces... I still don't see a strong argument for avoiding "using" in source files. Jingo, you're one of the few people on this board who consistently knows what they're talking about, but I have to generally disagree on this one. If you're putting a ton of crap into the global namespace that has the same names as the things in std then yes, it would be a bad idea to declare "using namespace std;", but I can't think of a reason a knowledgeable C++ programmer would intentionally do something like that, especially in a large codebase.
Emmanuel Deloget
Emmanuel Deloget
Quote:
Original post by bobstevens
The usual advice is never to use "using namespace" in a header file. I think some people have twisted that advice around in their heads because they like typing a ton of annoying an unnecessary stuff.

Seriously... who would use "std::string string" anyway?


I do. Continuously, professionally. I began to use this in 1999. Nearly 6 years of "std::string", "std::cout" and "std::endl". Phear me [wink].

It is not that unnecessary. In the pro context, you'll have to deal with multiple kind of source code. A library you've just purchased can have been written by a lazy programmer. Maybe he defined another function called sort(), for example, preventing you from using the std::sort function in algorithm if you used the "using namespace std" clause.

Therefore, I find it a good habbit to prefix std things with std::. It do not cost much time and can be useful.

Regards,
Zodiak
Zodiak
Ok guys, I see that everybody is against 'using namespace std;' so I guess I'll have to learn to prefix stuff. But seriously, if it's a simple TicTacToe game with one cpp file, I think 'using namespace std;' is justified.

Thanks, BTW!
I'd definetly say that a glass is half-empty!
Jingo
Jingo
Quote:
Original post by bobstevens
Quote:
Original post by Jingo
I can imagine the hell that would cause in a work enviroment where classes may often have the same name, and source files often exceed 100k lines of code. Having to search through the file to see which namespaces have been injected into the global namespace. O the fun.


If you're a person who prefers to prepend the namespace to everything, you'll never have to worry about what was injected into the global namespace since you'll never be using it. Right?

Ambiguities are easily resolved between multiple namespaces... I still don't see a strong argument for avoiding "using" in source files. Jingo, you're one of the few people on this board who consistently knows what they're talking about, but I have to generally disagree on this one. If you're putting a ton of crap into the global namespace that has the same names as the things in std then yes, it would be a bad idea to declare "using namespace std;", but I can't think of a reason a knowledgeable C++ programmer would intentionally do something like that, especially in a large codebase.


Its not so much the compiler errors, they are trivial to fix. It is the problem of readability. The compiler knows what namespaces are being used, the user does not, and in a large codebase it is difficult to find.

The C++ standard library already comes prepacked with a 'ton of crap' that is in the global namespace and also in the std namespace, namely all the functions inherited from C.

Is it obvious which version of sin is called in this code?

#include<cmath>#include<math.h>using namespace std;int main(){    sin(1.0);  }


Is it even obvious if that code should compile or not?

I don't think you have yet given a reason why using namespace std; is a good thing to do. In the cycle of software development you don't really save any meaningful coding time by typing it, but you introduce non-obvious ambiguity into the code by using it.
Zodiak
Zodiak
I can give you a good reason: if you are sure that you will be using only std, I mean, if you are sure that there won't be any conflicts. C++ is famous for being just a hammer, not a hammer, nails, bricks, blueprint, and a bunch of construction workers. Therefore if you are sure that using namespace std; won't cause any trouble, go ahaid.
I'd definetly say that a glass is half-empty!
Zahlman
Zahlman
In all seriousness - this is one of those issues where some thought is required - continually. If you're employed as a programmer, you're being paid to make exactly these kinds of decisions.
Endurion
Endurion
If it's too much to type for you you can always make a middle solution:

Use typedefs throughout. Typedef the used types to a easy short name for you. This helps also if you later want to exchange one string class for another. One change, done. (Can happen, as std::string isn't optimal for low ram machines due the internal 16 byte buffer for example).

Again, if you do, put that typedefs in a namespace on their own :)
Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.