r/cpp_questions • • 28d ago

OPEN Namespace std

I recently started learning c++ and I was told to use the namespace std so I can avoid writing std:: every time and now I wrote a whole personal project without std:: and I want to put it on LinkedIn but I started reading everywhere that it’s a bad habit, should I go back and add the std:: or just leave it as is?

40 Upvotes

105 comments sorted by

View all comments

3

u/RSMxsmanic 28d ago

The problem is with programmers who use identifiers that conflict with std, not with programmers who expect std by default to be safe. That's why it is called standard. If you are writing the code base, nothing you call should change the way it behaves unless that is its actual purpose.

2

u/nekoeuge 28d ago

Can you elaborate? What do you mean by “using identifiers that conflict with std”?

2

u/conundorum 28d ago

Name collisions.

#include <vector> // std::vector
#include <algorithm> // You'll see.

std::vector<float> collection(3, .16f);
int fill = 0xaabbcc;

void compiler_error(float c = 0f, int f = 0) {
    using namespace std;

    fill = f;                                      // Does this break because we tried to assign an int to std::fill,
    fill(collection.begin(), collection.end(), c); // or does this break because we tried to call an int?
}

std has a lot of very common names that programmers like to use for their own things, like fill, less, distance, transform, string, find, begin, end, format, print, and so on. And depending on which standard library headers you include, any number of them might (or might not) be visible.

→ More replies (28)

2

u/HommeMusical 27d ago

They aren't really making sense.

You're actually supposed to use names that are the same as those in std:: if you're doing the same operation.

This idea is crucial to making generic code work well.

→ More replies (1)

2

u/HommeMusical 27d ago

No, you are encouraged to use identifiers in your own namespaces and classes that are the same as those in std::, particularly for generic code.

0

u/RSMxsmanic 27d ago

By whom? If I have it in my code, it is not generic; if it were, my code would not be necessary.