Click to See Complete Forum and Search --> : which is better to use STD lib.?
liuty
March 27th, 2003, 08:33 PM
there are two methods to use STD lib.
1.using namespace std;----- use once
2.std::string s;-------------- use it everywhere
which is better?
Bob Davis
March 27th, 2003, 09:13 PM
It's really hard to say which is "better" in this case. It depends. If you have a lot of instances where "std::string" would occur in your code, you may want to bring in the entire namespace. Or, if you use other objects from the namespace, like cout, cin, std::vector, std::list, or other standard library members, you might want to bring in the namespace. Alternatively, if you just use the std::string class, you could use this:
using std::string;
This will allow you to omit the std:: qualifier from the class name when referring to strings. You might want to do this if you want just the string class, or if you're worried that you might have classes or objects with identical names than some standard ones that may conflict if you bring in the whole namespace.
galathaea
March 27th, 2003, 10:30 PM
In addition to Bob Davis' great points, it also common to not want to bring the entire namespace std into a header file, and many get rather squeamish at bringing any namespace members into headers as well. Since lots of client translation units may eventually include your header, it is usually considerate to not pollute those translation units beyond their permission. So your headers should probably use fully qualified namespace names without usings. Your cpp files are basically personal preference, as they are your translation units, you have full namespace control, and you need not worry about client code polllution.
Andreas Masur
March 28th, 2003, 02:36 AM
Originally posted by liuty
there are two methods to use STD lib.
1.using namespace std;----- use once
2.std::string s;-------------- use it everywhere
which is better?
Well...actually there are four...
// Using the full member name, including the namespace it belongs to:
std::cout << "Hello World";
// By taking advantage of Using-Declarations:
using std::cout; // This declares cout in the current
// scope as synonym for std::cout
cout << "Hello World";
// By taking advantage of Using-Directives:
using namespace std; // Which specifies that the current
// scope can refer to names in the
// 'std' namespace without using
// full qualifiers. This is mostly
// used when porting legacy code.
cout << "Hello World";
// Using aliases:
namespace X
{
namespace Y
{
class Z { ... };
}
}
X::Y::Z // The full qualifier for 'Z' is
// 'X::Y::Z'
namespace w = X::Y; // This declares 'w' as an alias for
// namespace 'X::Y'
w::Z // Access 'Z' using 'w::Z'
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.