CS253

CS253: Software Development with C++

Spring 2017

Symbol Ambiguity

See this page as a slide show

Symbol Ambiguity

or

“Them there namespacies is trickier then I done thought!”

using namespace, C++03

C++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++11

C++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. ☠ ☠ ☠ 😱 😱 😱

Explicit std::, C++03

C++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.

Explicit std::, C++11

C++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.

Selecting using, C++03

C++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.

Selecting using, C++11

C++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?

What is best?

Similarly …

Your choice!

Modified: 2017-04-03T14:45

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building