or
“Them there namespacies is trickier then I done thought!”
using namespace
, C++03C++03 (:c++03:)
#include <iostream> #include <utility> using namespace std; void move(string s) { cout << "moving " << s << '\n'; } int main() { move("beta.txt"); }
move
wants an argument of type string
, but we gave it
"beta.txt"
, which is a C-style string, of type const char *
.
Still, a conversion exists between the two, so it works.
using namespace
, C++11C++11 (:c++11:)
#include <iostream> #include <utility> using namespace std; void move(string s) { cout << "moving " << s << '\n'; } int main() { move("beta.txt"); }
Oops! C++ 2011 introduced std::move
, which is a better
match for the "beta.txt"
argument, so std::move
got called!
We changed nothing except the compiler version, and the code behavior changed. ☠ ☠ ☠ 😱 😱 😱
std::
, C++03C++03 (:c++03:)
#include <iostream> #include <utility> void move(std::string s) { std::cout << "moving " << s << '\n'; } int main() { move("beta.txt"); }
Some people avoid using namespace
for this reason,
and sprinkle their code with std::
. It's not pretty.
std::
, C++11C++11 (:c++11:)
#include <iostream> #include <utility> void move(std::string s) { std::cout << "moving " << s << '\n'; } int main() { move("beta.txt"); }
However, it works.
using
, C++03C++03 (:c++03:)
#include <iostream> #include <utility> using std::string; using std::cout; void move(string s) { cout << "moving " << s << '\n'; } int main() { move("data.txt"); }
Some people apply selective using
declarations.
It's not pretty, either, but at least the tedious part is all together
at the top of the program.
using
, C++11C++11 (:c++11:)
#include <iostream> #include <utility> using std::string; using std::cout; void move(string s) { cout << "moving " << s << '\n'; } int main() { move("data.txt"); }
And it works.
Do you carry an umbrella every day, or only when the weather report predicts rain?
If you carry an umbrella every day, then you’re always dry, but you have to carry a stupid umbrella all the time.
If you only carry it when rain is predicted, then you’ll get wet once in a while. However, this isn’t the end of the world.
It’s a trade-off. Which price do you want to pay? Constant carrying, or occasional moisture?
Similarly …
using namespace
, you pay the price of your code
being littered with std::
prefixes.
using
declarations, you have to keep adding
them as you change your code.
using namespace std
, then you’ll have a nasty problem
to track down once in a blue moon.
Your choice!
Modified: 2017-04-03T14:45 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |