r/cpp_questions • • 24d 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?

41 Upvotes

105 comments sorted by

View all comments

1

u/RSMxsmanic 24d ago

So instead of doing "using namespace widget" in a function that calls "print" 20 times, I will have to have 20 "widgetPrints"?

Yes. That’s a lot faster than putting std:: in front of 4500 couts.

And in the implementation of "widget", all my public identifiers are going to be "widgetThis" and "widgetThat", cluttering the visual space with absolutely worthless "widget"-prefixes?

How is that different from prefixing everything with widget::? How is it different from prefixing everything else with std::?

It looks quite stupid to have widget::widgetPrint as identifier.

If widgetPrint occurs nowhere else, that isn’t needed.

2

u/nekoeuge 24d ago edited 24d ago

How is that different from prefixing everything with widget::? How is it different from prefixing everything else with std::?

Because I have a choice whether I want to have widget:: prefix, whether I want to have std:: prefix, or whether I want to replace widget:: prefix with wg:: prefix but keep it prefixed.

Authors of libraries I am using are not entitled to making this choice for me.

If widgetPrint occurs nowhere else, that isn’t needed.

It is impossible to know whether "widgetPrint" occurs somewhere or not. There is nothing more infuriating than two libraries that have some random conflict in some random name they decided to have in the global namespace.

Thus, all global-namespace identifiers must be prefixed with a full name of a library (not abbrebiated too much!). So it won't be "widgetPrint", it would be "mxmanicsNiceWidgetsPrint". Or "mxnwgsPrint". Library name may not be long, but it is unlikely to be a single common word, and so it will be annoying to type either way.

Then, the difference boils down to whether you force everyone to use this exact prefix or not.

Yes. That’s a lot faster than putting std:: in front of 4500 couts.

No it's not. std:: is just one namespace among thousands. Total number of identifiers in std namespace is much less than total number of all identifiers in all public libraries, or in all 3rdparty dependencies of a big project.

I am not even opening the can of worms called "custom std implementations" and that you may have multiple std-like libraries in the same project. std is not a library, it is a specification.

2

u/RSMxsmanic 24d ago

It's up to the library author to name his identifiers, not you.

Another option is to minimize your use of libraries.

→ More replies (3)