Question

should one use 'using namespace std' or not ?

Asked by: Infinity08

As became clear in this question :

        http://www.experts-exchange.com/Programming/Languages/CPP/Q_24645383.html

there seems to be a difference of opinion on whether or not to use the using directive for the std namespace.

So I decided to open this question for free discussion about the subject (see the question title). Let's keep it on the topic of 'using namespace std' only ;) Posts will be accepted in the end based on their merit in the discussion (ie. not whether they correspond to my view or not).

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-12 at 05:52:04ID24646218
Tags

c++ using namespace std

Topic

C++ Programming Language

Participating Experts
7
Points
500
Comments
71

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. using namespace std
    Hello everybody. I have a little problem in my Program. I want to make an array via vector<CComVariant> , but when I insert the "using namespave std;" on top of my includes, there will be much errors. I tried the following, without success. What is the corr...
  2. Where to place "using namespace std"?
    I have two simple questions which I cannot solve. 1. Where do I place the "using namespace std" when using the STL? The reason I ask is that I always placed it at the top of the file (translation unit) when using GNU (g++). My programs always compiled perfectly....
  3. <cstring> and std namespace
    should all of the standard C functions be included in the standard namespace when you use the C++ header files? For example, I include <cstring> and <cctype> and I can say "std::isspace", but VC.NET will complain about "std::iswspace" not bein...
  4. using namespace ::std::rel_ops;
    hi experts, what does it mean by "using namespace ::std::rel_ops;" how is it different from "using namespace std;" thanks.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Infinity08Posted on 2009-08-12 at 05:59:23ID: 25078215

I'll start off with my own view.

I never use the using directive 'using namespace std;' for the simple reason that you cannot guarantee that it won't cause problems. Of course that means that you have to either use using declarations (genre 'using std::cout;') or use the explicit namespace qualifier std:: everywhere, but the extra type work is a small price to pay to avoid certain hard to track down bugs.

Personally, I don't even use using declarations, and always specify the std:: namespace qualifier explicitly wherever needed, simply because it makes explicitly clear that I really want the symbol from the std namespace and not from another namespace.

If you're not convinced of the potential pitfalls of adding 'using namespace std;' in your code, take a look at the below sample code. I'm sure we can agree that this is not an exotic example. Try taking out the 'using namespace std;' line to see the difference.

#include <iostream>
#include <algorithm>
#include <cmath>
 
using namespace std;
 
double min(double a, double b) {
  return (fabs(a) < fabs(b)) ? a : b;
}
 
int main(void) {
  std::cout << "If our own min method is called, this should be 5 : " << min(-10, 5) << std::endl;
  return 0;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: ZoppoPosted on 2009-08-12 at 06:06:16ID: 25078280

Hi,

I prefer not to use 'using namespace std' for a complete .cpp file.

This results from the fact that I some time ago had to port some real old code (mixed C/C++, no STL, not written by me) into our application. Unfortunateley there in some files a 'list' (not STL) was typedef'd, in other places variable names like 'string' were used.

This lead to lot of compiler errors (and caused lot of effort to solve them) since our application even used 'using namespace std' in lot .cpp files.

Therefor my preference is to write 'std::' where I need if it's not too exhaustive - otherwise (seldom) I use 'using namespace std' within a function or a class, but never in global scope.

But, of course this is just a opinion/habit.

ZOPPO

 

by: jaime_olivaresPosted on 2009-08-12 at 06:26:44ID: 25078468

Well, as I don't use to use 3rd party libraries, it is not usual for me to have conflicts with namespace std.
When I need to use some 3rd party code, I prefer to "migrate" it to fully-compliant ANSI C++ library or MFC library (i.e. using CString or CList), depending on project. Also I eliminate all the functionalities that I don't need and rename variables according to my standards. I think this extra effort is a good practice and makes all source code cleaner and easier to mantain.
Of course I know there are cases where you cannot modify library code, but I think that almost always there is a possibility to have a well written C++ code.

 

by: ikeworkPosted on 2009-08-12 at 06:58:14ID: 25078743

Hi Infinity, nice one:)

vector is a good example for a collision too. Almost every math lib has a class called like that, and there is std::vector.

Good news is, its not a critical issue mostly, since compiler will complain, if you have

using namespace std;
using namespace mymath;

vector v; // << compiler will complain here or later on when using the object or pass it to another function.

But usually I try to be on the safe side, so I share your opinion about the "using namespace". But certainly programmers are lazy, and so am I, so I found myself typing it in a c-file every now and then ;)

But certainly I never use it in header-files, this is the only important rule about it to me. Whatever you do in c/c++ files, its mostly undone with a quick *replace*. So its more a matter of taste or clean style, than a critical issue.

Btw. I dont agree with your example. To me a min/max function that takes the abs() of a value is indeed, well I wouldnt call it exotic, rather confusing and badly named. ;)

ike

 

by: peprPosted on 2009-08-12 at 06:58:42ID: 25078749

In my opinion, any such rule must not be a dogma -- nor using the 'using namespace std;', nor not using it.

I fully agree with the fact that not using the 'using namespace std;' may be the most safe way. But there are also other points of view. One of them is "you should follow the (un)written style rules of a company/project. Another point of view is "readability" of the source code -- I consider that very important.

Programming is the process of transforming our ideas into a formal description. A programming language is that much successfull in a problem domain how much it gives us one-to-one mapping between the abstractions and the programming constructs. This is from one point of view.

But also, we sometimes need to read back the code and build the abstraction in our mind. This way, the syntax of the source code is important. And not only this. The source code must be syntactically correct but also "nicely written" (good style).

Our mind has the ability to work with formally slightly incomplete ideas if we know the context of our thinking. Within that context, we tend to express the things rather briefly, informally. That is because the mental model of the solved problem is actually in our mind and not formally written elswhere. We are able to describe the mental picture from some other points of view to clarify the communication. The mental picture of the problem is important, not the small syntactical nuances.

This way 'using namespace std;' reflects the 'mental contex' of the problem inside of a single .cpp file (it should be also discussed what one .cpp should contain). It allows the code inside the .cpp be written more briefly. It can be read easily. From that point of view, the repeating 'std::' does not help to clarify the goal very much. In my opinion, if it works, we should always prefer the more readable form.

Of course, there may be exceptions -- like the sample code above. But the truth also is that this is caused also by historical reasons. The min() is quite a problematic thing. The reason is that it is used to express a well known abstraction from mathematics. Because of that many people want to call it that name. The truth is that there are functions and macros of that name (also MIN, Min, etc.). The truth also is that one should be aware of that historical problem where no namespaces were available -- one should sometimes follow the earlier recommendation "give your function a name that is likely not to be confused with the existing ones".

Still, I consider the above example the good one that illustrates when we should avoid the 'using namespace std;'.

On the other hand, this is very rare case. The most of source-code files does not contain similar things and it would be a pity not to use the more readable form.

 

by: Infinity08Posted on 2009-08-12 at 07:51:07ID: 25079315

Great start :) Some good points are made. Some more thoughts based on them :


First, the example code I gave is not something I came up with - it's something I found in existing code while tracking down a bug (which turned out to be caused by this). I agree that the name of the function could have been chosen better, but the point of the example is that the person that wrote the code expected his own min function to be called, but that wasn't the case.


Then, even though I agree that you can write 100% correct code while adding 'using namespace std;', you're usually not the only one working on the code. And not everybody might be as familiar as you with the std namespace. (the 'you' is generic here, and doesn't refer to anybody in particular). More specifically :

(a) you have to know all symbols in the std namespace to make sure that none of them clash with your own symbols
(b) you have to be sure that symbols that might be added to the std namespace in the future (C++0x is coming up soon) won't clash with any of your own symbols

An experienced C++ developer will know the large majority of all symbols currently in the std namespace (ie. the ones from (a) above), but most likely not all of them. However, he will never be sure about the symbols from (b).

In short, making sure the addition of 'using namespace std;' doesn't cause any problems requires a lot more effort than it would have taken to simply specify std:: explicitly. Especially, if at some point in the future, you'll be required to 'port' your code to a more recent version of C++, because you'll need to go over the entire code to make sure that there are no symbol clashes.


The readability argument is a good one of course, although I don't necessarily agree that adding std:: makes things less readable. More verbose, yes, but proper formatting can make up for that ;)

 

by: itsmeandnobodyelsePosted on 2009-08-12 at 07:58:52ID: 25079388

I am using C++ for about 17 years and only for the last few years some of my projects make use of namespaces at all. When using older libraries I generally have no problems regarding namespace std cause my classes begin with a capital letter. I rarely used global functions and never used names like 'string' or 'list' as variable names, so I can't remember one single naming conflict though it may have occured the one or the other with the years.  

Personally, I didn't use the std:: prefix when I started to using (learning) STL (about in 2002). Then in 2004/2005 I had a phase here in EE where I used std:: in every sample code same as Infinity does. I ended that phase after an asker complaint about readibility of some sample code. It was somewhat like
 
    std::map<std::string, std::pair<FuncPtr, std::vector<std::vector<AnyClass> > > >::iterator it;

You may say that

    map<string, pair<FuncPtr, vector<vector<AnyClass> > > >::iterator it;

wasn't so much better or that a typedef could have helped out. But for sample code you hardly make typedefs and the sample code had about 50 lines where nearly each has a few std::  prefixes. Those prefixes made the code uglier than it had to be, and the complaint made clear for me that the main goal when adding sample code in a comment was to explain a concept and not to provide full code which could be copied and would compile in any environment. If both could be achieved with a code sample it is fine but if not the first goal is more important than the second (especially as namespace errors hardly compile and conflicts with namespace std generally are less likely with newer C++ code. So I never heard of a commercial third party library which conflicts with STL). That thread was the initial trigger for me to further omit the std:: here in EE beside of header file samples and I am deeply convinced that it was a good decision as many askers were newbies who might get scared from those kind of coding.

>>>> But, of course this is just a opinion/habit.
Same applies for me.


 

by: itsmeandnobodyelsePosted on 2009-08-12 at 08:14:36ID: 25079580

In the initial thread for that discussion I used the following sample code

     ostringstream oss;
     oss << right << setw(3) << (int)c
           << "  0x" << right << setw(2) << setfill('0') << hex << (unsigned int)c;
     cout << oss.str() << endl;

It would have been

     std::ostringstream oss;
     oss << std::right << std::setw(3) << (int)c
           << "  0x" << std::right << std::setw(2) << std::setfill('0') << std::hex << (unsigned int)c;
     std::cout << oss.str() << std::endl;

where probably everyone could see that the std:: prefixes take too much room and don't add anything to the message I wanted to tell with those statements.


 

by: Infinity08Posted on 2009-08-12 at 08:16:48ID: 25079608

For the record : we're not discussing how to post on EE (that's a matter of taste). We're discussing how to write actual code (for a real world project).

 

by: itsmeandnobodyelsePosted on 2009-08-12 at 09:03:19ID: 25080072

>>>> we're not discussing how to post on EE (that's a matter of taste).
You are the boss.

 

by: jaime_olivaresPosted on 2009-08-12 at 09:59:20ID: 25080544

I would like to focus on these comments:

>> a) you have to know all symbols in the std namespace to make sure that none of them clash with your own symbols

We can extend this concern to all .net:
.net code will be really unreadable if don't work with:
     using System;
     using System.Collection.Generics;   // for handling arrays, dictionaries, etc.
or
     using System.Windows.Forms;   // for a winforms application

Developers cannot know all the vast set of .net classes under those namespaces, but the point is:
You have to be confident with your compiler, it shall detect all the inconsistencies.

>>(b) you have to be sure that symbols that might be added to the std namespace in the future (C++0x is coming up soon) won't clash with any of your own symbols
Again the same point. I am sure compiler makers have thought on this issue.

 

by: WhiteMagePosted on 2009-08-12 at 11:14:20ID: 25081242

The current C++ standard allows you to either use "using namespace std;", "using std::string;", or "std::string".  Therefore, you can't say that it's bad.  Just like there is no law against passing gas in public, it's just frowned upon.  And like it's already been said, it depends on the standards set by your company, organization, and/or colleagues.  At your house with your friends, it's okay to "let one rip," but not in the office environment, unless there's a standard saying that you must do it.  And in my opinion, little choices like this add to the artistic value of source code.

Having all that been said, I prefer to use "std::".

Why to use "std::"?
-It lists all of the functions and variables under that namespace (in a good IDE), which is pretty convient.
-Some argue that it means more unnecessary typing, but it's just 5 characters long, and in certain circumstances (again, with a good IDE), it actually means you type less.  You can type "std::really" then push enter for "std::really_long_variable_name" or something.  Although, you could argue against this by using the global namespace "::".  But I never see people that don't use "std::" use "::".
-Again, like everyone else has already said, it's good for code conflicts and future code conflicts.  I'm free to type "std::string string;" without any problems; I can create my own string class (in my own namespace of course); etc.
-It definitely looks cooler, and when you show your code to friends that don't know anything about programming, it looks more impressive (ew, shiny things).  The girls definitely think you're hotter for using "std::".  I've gotten so many numbers by leaving "std::beautiful thatbe(you);" on my restaurant receipts.  They gave me their numbers in binary.


When I write code for new programmers, I always use "std::" to kinda edge them into a healthy habit, but I really could care less if someone uses it or not.  When I write short programs that need to be written quickly, I almost always use "using namespace std;"  But if you plan on writing a freeware game engine available online, you better use "std::".  I can't think of anything else to say...just give me points!

 

by: Infinity08Posted on 2009-08-12 at 15:34:40ID: 25083770

>> You have to be confident with your compiler, it shall detect all the inconsistencies.

I haven't found any compiler that is intelligent enough to catch all namespace related mistakes. For example, in the code sample I posted earlier ... Do you know any compiler that would throw a warning about that ?

It would sure be nice, and if one exists, I'd definitely like to try it out. But I'd doubt it, since the compiler would get extremely complicated to be able to find these kind of mistakes.


>> just give me points!

Hehe ... Patience ;) We've got some interesting thoughts already, but I'm sure there's more where that came from :)

 

by: peprPosted on 2009-08-12 at 23:18:44ID: 25085756

All we are driven by our own experience. I have heard somewhere, that we usually spend one 3/4 of our time to argue/think for our own opinion and only 1/4 of time for the opposit opinion. This may be the reason why we all are so convinced that "I am right, not you!".

Infinity08 has shown a example that illustrates the danger of 'using namespace std;'. No doubt, it goes beond the simple kind of thinking about using the directive. It shows that not using the directive solves the problem.

In my opinion, extensive use of 'std::' is OK for widely shared libraries where you do not know what could be pulled via include into your .cpp file. Still, the header is more important. The .cpp will be compiled to a separate binary .obj and the 'using namespace std;' could be viewed as "the implementation detail" for each separate .cpp.

We could possibly discuss whether the #include discipline is not even more important than 'using namespace std;' in the .cpp file.

In my opinion, not using the 'using namespace std;' (and the like) is rather "mechanical" advise, very formal. It is not clear to me how big part of all problems it solves and whether the importance of doing so could not be masked by doing "more terrible" things that are not that visible.

What C++ standard says about what min() will be used in the snippet?

 

by: Infinity08Posted on 2009-08-12 at 23:41:29ID: 25085843

>> We could possibly discuss whether the #include discipline is not even more important than 'using namespace std;' in the .cpp file.

Definitely agree with that ... But that's another discussion ... Maybe I'll open another one for that ... if someone doesn't beat me to it heh.


>> What C++ standard says about what min() will be used in the snippet?

The C++ standard algorithm min is defined using template arguments. And the compiler has to prefer to pick the closest match (paragraph 13.3 in the C++ standard, which deals with function overload resolution).

Since in the snippet, min was called with two int's as parameters, the compiler prefers to pick the templated standard min function (with T = int), rather than do an implicit cast to double to call our own min function. When the standard min function is not made visible by the std using directive, it will do the implicit cast to double for both parameters, and call our own min function.

 

by: WhiteMagePosted on 2009-08-13 at 07:04:58ID: 25088321

Personally, I feel a similar feeling here as when discussing multiple inheritance.  I think that 100% multiple inheritance is useful, and I have used it in my projects, but it definitely shouldn't be overused.  It all depends on the project, the environment, the people you're working with, etc.  Similarly, I find "using namespace std;" useful, but again should be used more rarely then the other counterparts (i.e., "using std::cout;" or "std::cout").

Really, if every new programmer used aut_ptr or boost's shared_ptr, I could care less if they use "using namespace std;"  I'm so tired of seeing memory leaks in C++ programs.  It happens to everybody...

 

by: Infinity08Posted on 2009-08-13 at 08:10:29ID: 25089223

I agree that there are more important issues than whether or not to use 'using namespace std;', but nevertheless it's an interesting iscussion point imo.

Ok, it seems the discussion has slowed down a bit, so how about a summary of what we have so far. Feel free to correct me and/or add to the summary :


advantages of using the using directive ('using namespace std;') :
(a) convenience : less type work
    counter argument : although convenience is nice, there are more important considerations (it's only 5 characters)
(b) readability/brevity : the code isn't riddled with std:: namespace qualifiers, which makes it easier to process/read
    counter argument : proper formatting of the code can help with this, although it doesn't solve it entirely


advantages of using the using declarations ('using std::cout' etc.) and/or explicit namespace qualifiers ('std::') :
(a) robustness : avoids certain hard to track down bugs
    counter argument : these kind of bugs aren't common in well written code, and a good compiler might catch many of them anyway
(b) easier integration of third party code : if the third party code defines some of the same symbols as in the std namespace, it can still be used without any issues
    counter argument : wherever possible, the third party code can be re-factored to avoid namespace problems
(c) future proof : future additions to the std namespace won't have an impact on your current code
(d) doesn't require detailed knowledge of the symbols defined in the std namespace
(e) convenience : aids name completion features in certain IDE's


Some general arguments made :
(a) always follow the company/project code style guidelines and standards
(b) following certain naming and other style rules (to avoid collisions with symbols in the std namespace) could make this discussion largely irrelevant
(c) we all seem to agree never to put 'using namespace std;' in a header file
(d) it's not a black-and-white issue - in certain situations one approach is better, in other situations the other approach is preferred

 

by: peprPosted on 2009-08-13 at 09:23:57ID: 25090146

Just a note to "(a) convenience : less type work". I feel that there are various kind of laziness. One of them leads to new inventions. Another is just a synonym for sloppiness. Some may be related to inability to type (fast keyboard typing). It makes no sense to discuss the issue from the point of view of sloppiness. Some programmers are just too lazy to be good in their job, ever. Fast typing can be solved using more training (10 fingers typing courses/training applications) or by specialized editors (macro expansions, expansion of partly written identifier by IDE,...).

This way, the readability is the only reason for me.

Now, I would like to introduce some idea that could be implemented in IDE (I do not know if it was or not). Some context first. It could be seemingly off topic, but I believe it is related to the discussed issue.

The older of us (if not all of us) probably know how strange it looks now to read the source code without syntax highlighting. If it could look like some extra decoration earlier, I consider it very important when looking at and even typing the source code. When making typo in a keyword, one "gets the strange feeling" that something is wrong in the time of typing. If I had an editor where the syntax highlighting could be switched on/off, I would probably never switched it off (possibly changing some disturbing colours, but not switching off). The reason for letting it on is the readability!

Another newer feature related to editors is "folding". Id may depend on what kind of work you do. It depends also on the length and structure of the folded document. The reason for mentioning that feature is that a folded document changes visually. The visible part is the one that we want to work with while suppressing the other parts that are not that important "just now". Similarly to the folding, it would be nice to have...

The new feature could be called something like "namespace highlighting". Say, the std::cout would be displayed on the screen as cout but in a visual style that identifies the namespace std -- say some not very agressive background color or some frame around, or whatever reasonable. This way, the source text would be slightly different than what is really written in the source -- the namespace identification changed visually from the text to a graphic form. This way the feature would be something like crossbread between folding and syntax highlighting. Definitely, the result would be more readable.

Would you like such a feature? Is it implemented anywhere?

 

by: WhiteMagePosted on 2009-08-13 at 09:46:22ID: 25090356

>>Some may be related to inability to type (fast keyboard typing).

This is an interesting point.  Someone with certain physical handicaps may be better off not typing as much.  Still, you can do "using std::cout;".  I'm sure there's not enough interest in it, but it'd be interesting to design a programming language for easier use by someone with injured hands or for someone who can't see very well (but of course can still see).  Although, these languages probably already exist, unintentionally by the designer, like Scheme and Ruby, where less code may have to be typed, although this is very debateable.  A good C++ programmer with many already made (by them or by someone else) classes can write extremely short code for complex programs.  An example would be using Simple DirectMedia Layer (SDL) or Boost.  Although, this is getting a bit off-topic...it brings up the question again that must programmers arrive at, that is usually answered with a firm No.  Can a universal programming language exist from which is the only one solely used?  Of course, this seems impossible, but if Quantum computers reach Sci-Fi levels, maybe this could seem more feasible.  Also, it'd be interesting to see a programming language created by a very large group of people based on voting or something (I don't know what), similar to certain Linux distros.  Anyway, this is way off topic, but just some thoughts for new posts and future discussions.

 

by: ikeworkPosted on 2009-08-13 at 14:00:38ID: 25092954

Just want to remind you guys, "std" is just an (simple) example. At my work we use lots of 3rd party libs and own libs and they all have nested namespaces. So rather than discussing a little "std" we should discuss it more general and keeping in mind, that there can be very long and nested namespaces..

 

by: Infinity08Posted on 2009-08-13 at 14:06:57ID: 25093023

The reason I made the question about the std namespace, is because it's very common - it's used it pretty much all C++ projects. Obviously the same conclusions/arguments made for the std namespace can be made for any other namespace. So, feel free to expand the discussion to general namespaces, rather than the specific std namespace ;)

 

by: ikeworkPosted on 2009-08-13 at 14:15:53ID: 25093107

My point is, although I tend to use "std::" as well, when it comes to nested namespaces, I mostly (like my collegues) use the "using namespace aaa:aa:aa" instead.
To me its rather a question of style (again not in the header) than a question of avoiding damage to the code.
We are yet to see a real example, where damage was done and the compiler did not complain. Sorry infinity, just because someone made really bad code, i wouldnt use it as an example. I mean, this function name was just wrong, even without the namespace issue, it makes damage to an application, because a collegue could use it for what its name suggests. If the function would do what it name suggest, it wouldnt be an issue, it would give the min value anyway, from a wrong function, but hey ;)
So again, for long nested namespaces I use the "using namespace", because the compiler will complain if the object was from a wrong namespace, at least when you use the object, calling memberfunctions, passing it to a function.

 

by: ikeworkPosted on 2009-08-13 at 14:17:47ID: 25093131

Ok i see, then i misunderstood the question. I thought it was a general one, and the "std" was just an example.

 

by: Infinity08Posted on 2009-08-13 at 23:20:41ID: 25095610

>> Sorry infinity, just because someone made really bad code, i wouldnt use it as an example.

I wouldn't call it really bad code. In this case, the reason it was there is because the software grew with time, and was maintained by different people.
Originally there was just a normal min function which behaved as you'd expect, and there was no 'using namespace std;'. Then at some point, a bug was discovered when in certain rare cases, negative values were processed incorrectly. It seems they went for the quickest way to fix that - by adding the fabs's. Still correct, although the function name was no longer the best choice. Then at some other point in time, a feature was added, for which the developer added the 'using namespace std;' and the <algorithm> include. And the rest is history lol - the original bug re-emerged mysteriously.

And that's the point I was trying to make earlier. If you have 'using namespace std;' somewhere in your code, there's a good chance it will cause a problem somewhere down the line. Maybe tomorrow, maybe in 10 years. Which is why I avoid it.

The discussion so far seems to revolve around convenience/readability vs. robustness. Some consider the chance it will cause trouble small enough to prefer making the code more readable by adding 'using namespace std;'. Others want to avoid issues, no matter how small the chance of them occurring, even if that means making the code more verbose.

 

by: jaime_olivaresPosted on 2009-08-14 at 05:51:07ID: 25097404

Let's analize again a parallel case:
There are other situations where suplicity can fool the compiler, like with variable names: library's versus class data members versus global versus local versus parameters. Then, how to be absolutely sure that you won't have an ambiguous situation  generated among several programmers? I think the answer is: conventions and disciplines.

STL libraries: use to be all-lowercase
Global variables: all uppercase (as traditional in C)
Class' data members: 1st upper case
Local variables: camel or hungarian notation?
Function parameters: I use to lead with an underscore

So, we can port these conventions to function names. If you don't use all-lowercase names for functions then you won't have unexpected use of the wrong functions.

 

by: evilrixPosted on 2009-08-14 at 07:33:09ID: 25098455

I joined this discussion very late (been on holiday) and given the length I only had time to skim it quickly...

...unless I missed it no one mentioned ADL (Argument Dependent Lookup), which complicates matters even more since it means you can use non-prefixed function names that are in a namespace if any of the arguments exist within that namespace regardles of whether using was used. That can be complicated even more by the fact that C++ will allow implementation to be implicitly rather than explicitly included in the same namespace as the original declaration, this can lead to some very oddly (in terms of expectation) behaving code.

From my side,  I always use explicit namespace prefixing for any standard or 3rd party library or anything from a header that I know will be picked up due to standard include paths (ie #include<> vs #include ""). I only "use" my own namespaces and, of course, only in .cpp files (it worries me how often I see code examples with using std in the header!).

 

by: itsmeandnobodyelsePosted on 2009-08-15 at 02:30:06ID: 25104656

>>>> Still correct, although the function name was no longer the best choice.
No, it wasn't correct at this point.

If some other developer would have moved the new overload of min to some other module - e. g. for using it a second time - you might have the pitfall before - without being namespaces were involved.

I remember issues with min when they changed it from macro to function. Though it was a compiler error, I had big problems to even spot the reason. It was then, when I decided to never overload C runtime functions in C++.

You now may argue that by using the STL template functions without prefix, in some cases I was using C++ overloads of the C runtime. But I never use STL template functions like min, max, ....

 

by: Infinity08Posted on 2009-08-15 at 03:26:39ID: 25104766

>> If some other developer would have moved the new overload of min to some other module

There was no overload involved, and the function was only used locally in the compilation unit. It was simply modified to fix a bug. Anyway, wrong or not doesn't really matter. The whole point is that a different function was called than expected due to the use of 'using namespace std;'. I think we're focussing too much on this one example, as if if we can (dis)prove this one example, we've (dis)proven the whole case.


>> I joined this discussion very late

Glad to have you back among the living, evilrix ;) ADL is an interesting consideration. It does indeed complicate matters, and there's no easy way around it, except to never call a function in one namespace with argument types from a different namespace. That can get pretty annoying/difficult to manage.


>> So, we can port these conventions to function names. If you don't use all-lowercase names for functions then you won't have unexpected use of the wrong functions.

That would work, but only for the std namespace. What if other namespaces are involved ?

In any case, namespaces were precisely put into place to avoid these problems. They allow different namespaces to define the same symbol. So, what you propose sounds like emulating namespaces by using naming conventions ... Why not simply use the namespaces then ?

In C, it's common to include the module name into externally accessible symbols to avoid conflicts between different modules (modulea_function vs. moduleb_function). This is the C way of having some sort of emulated namespaces. In C++, namespaces formalized this and made it more convenient (ie. modulea::function vs. moduleb::function).

They then decided to put all standard symbols into the std namespace to allow developers to define those same symbols in their own modules. 'using namespace std;' overrides this flexibility, which is fine if you don't need it (but you might not be 100% about that).

 

by: ikeworkPosted on 2009-08-15 at 04:02:00ID: 25104839

>> I think we're focussing too much on this one example

I disagree again infinity ;) I think the example is very important here.
Because for me the essence of your interesting question is:

       Is using the "std::" a matter of taste or a matter of good and safe programming style.
   
If we have a clean example, that demonstrates, that it is unsafe, not to use "std::", then the answer is clear, its the latter one.
If there is no such example, then it seems to me more a matter of taste.

The argument for future changes still stands. But this can be used for everything. Somebody in my company could decide to make the point-class only working in 5D space in 2 years. Shouldn't I use the point class then? I think its up to the engineers, that make the new classes/namespaces to make sure such collision are not to come. You cant prevent it from the other side.

    So again: A matter of taste or not?

I did not  100% make up my mind yet and I'm still curious to hear you guys, but I tend to be on the "Matter of Taste" side.


 

by: Infinity08Posted on 2009-08-15 at 05:01:03ID: 25105078

I like that approach, Ike. Let's see if we can come up with a better example that would without doubt show that 'using namespace std;' is unsafe. Anyone ?

 

by: jaime_olivaresPosted on 2009-08-15 at 07:56:46ID: 25105648

>>That would work, but only for the std namespace. What if other namespaces are involved ?

This can be solved by taking both approaches with moderation. My own rule is:
- Use always "using namespace std"
- Also use the namespace of the class you are implementing (well, this is obvious)
- Use the namespace of a library you are strongly using in the specific file. Let's say, a math library when implementing a Geodesic_coordinate class.
- Explicity qualify all other class names
- Follow the naming conventions mentioned to avoid collisions

 

by: WhiteMagePosted on 2009-08-15 at 09:41:46ID: 25106016

What about the example below?

In my opinion, I think it's better to not just "get around" such a problem by just making a naming convention that states all variable names must have the first letter capitalized.  A lot of libraries might not have the same class names as std, but I know that fellow workers or users of my library will name them as such, especially for gaming libraries which have a lot of the same names but different uses.  "Vector vector;", etc.

However, as mentioned earlier, I can see the need for it with long or lots of namespaces.  To me that is just poor designing, but still I wouldn't use "using namespace aaa:aa:a" unless it is inside a namespace itself:

namespace mylibrary {
  using namespace std;
  class MyClass {
  };
}

Or better would be to use "using aaa:aa:a:Func" within the class or the namespace.

What would be nice is to have a standard C++ website where you can register a namespace, so that you only have to have 2 short named namespaces such as below.  Then there are less worries, but still worries.

namespace mage {
  namespace ogl {
  }
}

Check the website, "mage::ogl" is taken, so change to "wmage" and register on website, etc.

But this is only a pipe dream, and I couldn't see working...

#include <string>
 
//Better support for Big5 charset
namespace Big5Library {
	class String {
	public:
		String() {
		}
	};
}
 
using namespace std;
using namespace Big5Library;
 
int main(int argc,char **argv) {
	String string;
	string stringForInputAndFileNamesAndConverting; //Short name
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window

 

by: peprPosted on 2009-08-16 at 14:38:34ID: 25110588

To "naming conventions" vs. "namespaces": Theoretically, all problems could be solved also for plain-names language by using specific (unique) prefixes of all identifiers. As was said above the "std::" could be also such a prefix. And if ':' was accepted as a caracter that could be a part of identifiers, then std::cout would be just another identifier with reserved prefix.

Apparently, namespaces not only allow to write such "prefix" of the name (with ':' in the name). The namespaces also allow you "not to use that prefix always and always". Apparently, long identifiers are less readable (from pre-namspaces era). Namespaces are a compromise. And various use of 'using std::cout;' or 'using namespace std;' are a kind of dirty ways to reach more readable form with some probability to make it better than in pre-namespace era.

Maybe, namespaces would be designed differently if they were used more in other languages when the C++ was designed. There may be different and possibly better approaches for solving the problem -- say the old idea of reflecting the existence of modules that are usually bound to source files. See the D programming language http://www.digitalmars.com/d/.

 

by: Infinity08Posted on 2009-08-17 at 01:17:53ID: 25112319

>>         String string;
>>         string stringForInputAndFileNamesAndConverting; //Short name

Your compiler would catch this though, so you would be able to fix it instead of it going by unnoticed. I think what we're looking for, is an example of a bug or other problem introduced by the use of 'using namespace std;' that goes by unnoticed, and is otherwise perfectly ok code.



pepr, yes, that's what I was referring to when talking about the C way of emulating namespaces. It has the serious downside of not being very flexible or scalable (especially when using many levels of nested namespaces) though.

But namespaces aren't specific to C++, and many languages implement it in a similar way.

Take the java packages for example. You can use 'import' to add all or specific symbols for a certain package into the current one ('import java.lang.*;', 'import java.lang.String;'). Or you can use explicitly qualified symbols ('java.lang.String').

Or modules/packages in Python. You can also import them ('from sys import *' or 'from sys import stdin'), and explicitly qualify them ('sys.stdin').

I can come up with many more that use the same approach to namespaces as C++. So :

>> Maybe, namespaces would be designed differently

It sounds interesting, but I'm not sure how we can improve on the concept (except for cosmetic improvements).

Obviously, C++ namespaces can be used in a different way than to implement modules, but they do allow you to do that. In fact, I'd say that is one of their primary purposes.

 

by: ZoppoPosted on 2009-08-17 at 02:14:37ID: 25112561

Maybe the attached one is a sample to discuss about - IMO it's correct code. I didn't test in other compilers, but with VS 2008 it works fine without 'using namespace std' and crashs as soon as 'using namespace std' is used.

The code swaps two instance's values. Without 'using namespace std' in line 4 it works fine and generates output like this:
> t1: 5 (0x0080DDB0)
> t2: 7 (0x0080DDE0)
> t1: 7 (0x0080DDB0)
> t2: 5 (0x0080DDE0)

When uncommenting the 'using namespace std' in line for the application crashs after the second line of output.

The reason is that the copy-constructor of 'CBase' doesn't instantiate the pointer 'm_pInt'. If calling 'swap' with references to 'CBase' objects the implemented 'void swap( CBase& t1, CBase& t2 )' is called which works fine, but with 'CDerived' object it seems to call 'std::swap' which crashes.

ZOPPO

#include "stdafx.h"
#include <iostream>
 
// using namespace std;
 
class CBase
{
	int*	m_pInt;
public:
	CBase( int n = 0 )
	{
		m_pInt = new int;
		*m_pInt = n;
	}
 
	CBase( const CBase& src ) { *this = src; }
	CBase& operator = ( const CBase& src )
	{
		if ( this != &src )
		{
			*m_pInt = *src.m_pInt;
		}
		return *this;
	}
 
	~CBase() { delete m_pInt; }
 
	int	GetValue() { return *m_pInt; }
	int* GetPointer() { return m_pInt; }
};
 
class CDerived : public CBase
{
public:
	CDerived( int n = 0 )
	: CBase( n )
	{}
 
};
 
void swap( CBase& t1, CBase& t2 )
{
	CBase tmp;
	tmp = t1;
	t1 = t2;
	t2 = tmp;
}
 
int _tmain( int argc, char* argv[] )
{
	CDerived t1( 5 ), t2( 7 );
 
	std::cout << "t1: " << t1.GetValue() << " (0x" << std::hex << t1.GetPointer() << ")" << std::endl;
	std::cout << "t2: " << t2.GetValue() << " (0x" << std::hex << t2.GetPointer() << ")" << std::endl;
	swap( t1, t2 );
	std::cout << "t1: " << t1.GetValue() << " (0x" << std::hex << t1.GetPointer() << ")" << std::endl;
	std::cout << "t2: " << t2.GetValue() << " (0x" << std::hex << t2.GetPointer() << ")" << std::endl;
 
	return 0;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:

Select allOpen in new window

 

by: ZoppoPosted on 2009-08-17 at 02:19:50ID: 25112590

Sorry, one thing I missed: Of course one can say the copy constructor of CBase is the problem since it should instantiate the 'm_pInt'.

But, even without that copy constructor implemented at all the swap even crashes with 'using namespace std' but doesn't without, but later on since the pointer 'm_pInt' of 't1' gets deleted after the swap functions called the destructor of 'tmp'.

You can try by just commenting out the line 16

ZOPPO

 

by: ZoppoPosted on 2009-08-17 at 02:22:33ID: 25112599

And one more addition: The crash only happens in DEBUG builds. In RELEASE build it may crash or set one of the both object's values to a undefined number. Which IMO is even worse since it's extremely hard to find such a bug.

 

by: Infinity08Posted on 2009-08-17 at 02:23:59ID: 25112604

I'm not sure how the std swap is implemented for VS 2008, but the crash might be due to the fact that your copy constructor doesn't perform a deep copy.

 

by: Infinity08Posted on 2009-08-17 at 02:26:34ID: 25112611

>> but the crash might be due to the fact that your copy constructor doesn't perform a deep copy.

Which means that if the temporary object in the swap function is deleted, it basically deletes one of the two original object's m_pInt pointers.

 

by: Infinity08Posted on 2009-08-17 at 02:35:23ID: 25112655

Ignore that lol ... I was a bit too pre-mature with my analysis heh. Although the problem still seems to be with the copy constructor, it's not because it deletes the m_pInt of another object, but because it tries to assign without allocating memory first.

Try this instead :

CBase( const CBase& src ) { m_pInt = new int; *this = src; }

                                              
1:

Select allOpen in new window

 

by: ZoppoPosted on 2009-08-17 at 02:38:46ID: 25112679

Yes, I know that this is the problem. But even it fails without any copy constuctor (and IMO adding a 'using namespace std' shouldn't force me to implement a copy constructor) and no matter how this can be corrected IMO it's a major issue that adding 'using namespace std' leads to a call of another 'swap' function as without.

 

by: ZoppoPosted on 2009-08-17 at 03:22:58ID: 25112879

ok, I modified the sample a little bit.

Now there's no copy ctor and no 'operator =' anymore. Even no temporary object is instantiated/deleted. It's a quite simple class which holds a pointer to a large memory buffer.

The 'swap' function is implemented in a way it just swaps the pointers. Thus it saves memory and performance compared with an implementation of a copy ctor and 'operator =' with deep copy.

IMO this code isn't bad code (except maybe the fact 'swap' is implemented as a global function - if it's implemented i.e. as a static member of CBase the error doesn't occur) since the 'swap' function works as expected without 'using namespace std' (it swaps the data the objects point to).

The behavior is the same as mentioned above: Works fine without 'using namespace std', with 'using namespace std' it crashes.

ZOPPO

#include "stdafx.h"
#include <iostream>
 
// using namespace std;
 
const int BUFSIZE = 10000000;
 
class CBase
{
	int*	m_pInt;
public:
	CBase( int n = 0 )
	{
		m_pInt = new int[ BUFSIZE ];
		m_pInt[0] = n;
	}
 
	~CBase() { delete [] m_pInt; }
 
	int	GetValue() { return m_pInt[0]; }
 
	int* GetPointer() { return m_pInt; }
	void SetPointer( int* pInt ) { m_pInt = pInt; }
};
 
class CDerived : public CBase
{
public:
	CDerived( int n = 0 )
	: CBase( n )
	{}
};
 
void swap( CBase& t1, CBase& t2 )
{
	int* pTemp = t1.GetPointer();
	t1.SetPointer( t2.GetPointer() );
	t2.SetPointer( pTemp );
}
 
int _tmain( int argc, char* argv[] )
{
	CDerived t1( 5 ), t2( 7 );
 
	std::cout << "t1: " << t1.GetValue() << " (0x" << std::hex << t1.GetPointer() << ")" << std::endl;
	std::cout << "t2: " << t2.GetValue() << " (0x" << std::hex << t2.GetPointer() << ")" << std::endl;
 
	swap( t1, t2 );
 
	std::cout << "t1: " << t1.GetValue() << " (0x" << std::hex << t1.GetPointer() << ")" << std::endl;
	std::cout << "t2: " << t2.GetValue() << " (0x" << std::hex << t2.GetPointer() << ")" << std::endl;
 
	return 0;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:

Select allOpen in new window

 

by: Infinity08Posted on 2009-08-17 at 03:35:11ID: 25112937

>> But even it fails without any copy constuctor

The compiler generates one for you that performs a shallow copy ;)

>> (and IMO adding a 'using namespace std' shouldn't force me to implement a copy constructor)

It can be argued that since you have a class that uses dynamically allocated memory, you should implement your own copy constructor and assignment operator to perform a deep copy, rather than the default shallow copy.

>> it's a major issue that adding 'using namespace std' leads to a call of another 'swap' function as without.

I couldn't agree more. But we're looking for a clean example that illustrates that.
It can be argued that in my earlier example, choosing a better name for the min function would have solved the problem too. Similarly, it can be argued for your example, that implementing the copy constructor and assignment operator correctly solves the problem too.

>> The 'swap' function is implemented in a way it just swaps the pointers.

That's more interesting :) But technically, you should still make sure that the copy constructor and assignment operator are either implemented correctly, or can't be called at all (by making them private for example).


Sorry for being picky ... We're on the same "side" ;) I'm just looking for the perfect example that no-one can refute heh.

 

by: ZoppoPosted on 2009-08-17 at 03:51:23ID: 25113020

> Sorry for being picky ... We're on the same "side" ;)
No problem at all :o)

> ... choosing a better name for the min function would have solved the problem too
Of course, this even can be sayd about my sample - but I think this is what we discussed above about style guides/code conventions.

> The compiler generates one for you that performs a shallow copy
I know ...

> or can't be called at all (by making them private for example)
That's right, but I guess people often won't think about doing this fir such a simple class

Further I found it may be a problem even if copy ctor and 'operator =' are implemented correctly. I.e. add attached code to CBase. In this case the application won't crash or produce wrong results but the 'operator =' is called three times when 'using namespace std' is used so it's bad for performace and needs more resources. Without 'using namespace std' it's much more efficient.

ZOPPO

	CBase( const CBase& src )
	: m_pInt( NULL )
	{ *this = src; }
 
	CBase& operator = ( const CBase& src )
	{
		if ( this != &src )
		{
			delete [] m_pInt;
			m_pInt = new int[ BUFSIZE ];
			memcpy( m_pInt, src.m_pInt, BUFSIZE );
		}
		return *this;
	}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: Infinity08Posted on 2009-08-17 at 04:07:44ID: 25113104

>> Without 'using namespace std' it's much more efficient.

Aha. I like that spin :) Let's see what the others have to say about all this ...

 

by: ikeworkPosted on 2009-08-17 at 08:36:17ID: 25115477

@Zoppo

Your example crashed, because the copy-ctor was not implemented properly. Using the std-namespace just made that clear. But the problem was not the namespace, it was the wrong implementation of your class. You MUST provide a proper copy-ctor and assignment-operator, if you have dynamically allocated memory in that class. That's got nothing to do with the namespace.

>> Without 'using namespace std' it's much more efficient.

In your example yes, because you programmed it that way. You overloaded the swap function with a more specialized version for your class. Then of course its faster. But you can't generalize that. You cant say in general "using namespace" is less efficient, I guess you agree there.

 

by: ZoppoPosted on 2009-08-17 at 08:47:08ID: 25115598

> Your example crashed, because the copy-ctor was not implemented properly
That's correct, and it's clear for me - and it even crashs when I don't implement the copy-ctor at all allthough I didn't change anything else than adding a 'using namespace std'.

Especially about the second sample I'm quite sure that it might happen a C++ developer doesn't implement a copy ctor and a 'operator =' as long she/he is sure none of these two are ever called.

> You cant say in general "using namespace" is less efficient, I guess you agree there.
That's not the thing I wanted to point out - it's that without changing anything else than adding the 'using namespace std' the path of execution has changed in an unexpected way thus decreasing efficiency in this sample.

IMO this sample demonstrates that 'using namespace std' can influence the robustness of source code.

 

by: WhiteMagePosted on 2009-08-17 at 09:23:44ID: 25115961

Well, as has already been show, using "using namespace std;" means that you have potential conflicts with every function and class within the standard with other libraries.  This means that during runtime you can use "string" or "vector" of one library when you were meaning to use the standard library.  I feel like the main point of C++ in the beginning was for a language that looked ahead in the future.  You write one class, then use that class everywhere, never having to write it again.  If you need to change it, you can change it so that all of the old code will still work properly (although some people don't) while having new, fresh code.

I can see a valid reason for wanting more readable code that required less typing.

But I can't see a valid reason for potentionally causing runtime problems in the near or distant future by exposing every standard class, function, and variable to the global namespace.  That is a lot of potentional problems.  Yes, you're still not 100% safe, and you never will be, but using "using std::" or "std::" will definitely better your chances of code that is more portable and more "future safe," as I think the designers of C++ intended.

For example, the following is rare, but why even chance it?  I don't get the point of chancing so many compile and run time problems just so you don't have to type 5 characters or just "using std::string" within a class or something.

#include <string>
#include "japanese/string"
#include <vector>
#include "gamelib/vector"

string foo("hello"); //ascii text converted to Big5 or UTF-16/32 charset
std::cout << foo; //run-time error (text is all displayed weird)
vector v(4.5,6.7,8.9); //compile-time error

Yes, I know this isn't the best example, but it simply illustrates the point I was trying to make.  Just like I know that when the program terminates, all of my memory is freed, but does that mean I shouldn't ever call "delete"?  No, of course not.  Now "std::" isn't as big of a problem as that, but we still need to think of the future.  However, I'm still fine with "using namespace std;" where appropriate or if your company requires this.  C++ allows this, so you can't say it's 100% wrong, but I think we can at least agree that using "using namespace std;" has more of a potentional for problems than using "std::".

 

by: ikeworkPosted on 2009-08-17 at 09:53:41ID: 25116188

>> but I think we can at least agree that using "using namespace std;" has more of a potentional for problems than using "std::".

Agreed :) But that means also, with the same arguments presented for "std", that you have to do it for every namespace you use, even nested namespaces.
We have a lot of it in our company. Big projects are not just written with STL and libc as you guys all know.
So if you want to be consistent, then the code becomes unreadable and hard to maintain.
"std" is as important as any other namespace for us.
And I think we agree, that namespaces with longer names then 3 characters have the same potentional for problems ;)

 

by: Infinity08Posted on 2009-08-19 at 03:15:42ID: 25131036

well, it seems this doesn't generate much more discussion. Unfortunately, we don't seem to have found a definitive reason (that everyone can agree with) to use one or the other. So, I guess the conclusion is that one chooses whichever is appropriate for the situation, making sure to be aware of the risks and disadvantages.

Any further thoughts ?

Suggestions for how to close this ?

 

by: Infinity08Posted on 2009-08-19 at 03:17:51ID: 25131052

Oh, and if someone other than me wants to make a final summary of the most important arguments, then that would be an obvious choice for the 'accepted' post, with the others being the 'assisted' posts.

 

by: evilrixPosted on 2009-08-19 at 03:26:22ID: 25131097

>> Any further thoughts ?
Well, I did write some code that demonstrated uncaught ambiguity when using ADL but decided against posting it because it was a little contrived (although it could happen in the real world).

In the end, I think what you do should be dictated by your coding standards... choose a method and stick to it. Code consistency is more important, if you know code you (and your team) write always follows a specific standard you can code to ensure everything abides to that standard.

 

by: ZoppoPosted on 2009-08-19 at 03:33:00ID: 25131130

I have one more thought - unfortunateley one which conflicts with my previous ones:

If i.e. someone uses STL lists in his code and later on wants to use a list implementation from another library/namespace which is implemented similar, but maybe better (i.e. faster or threadsafe) this would be very simple if a 'using std::list' was used instead of multiple 'std::list' all around in the code, because the used class could be 'switched' by just changing the 'using std::list' to i.e. 'using better_std::list'.

But I guess it very rarely happens that one has to do this, so for me it's not a reason to use 'using std::...'

And I fully agree with evilrix - when you work in a team it's quite important to use a consistent coding style.

ZOPPO

 

by: WhiteMagePosted on 2009-08-19 at 17:18:53ID: 25138473

On Zoppo's comment:

That's a good point.  A possible solution to that could be either doing a find & replace all on all documents in an IDE changing std::list to betterstd::list or possibly deriving from std::list and changing the function implementations if that is possible.

From what I've read here, I think that "using std::" or just "std::" has won at least with a 51% to 49% advantage or something close like that.  A really long namespaces with multiple namespaces seemed to have gone the other way, but I haven't read anything here that would make me think that "using namespace std;" should be used the majority of the time.  In most cases (even if that is 51%) overall in general use of C++ code that you write (in your lifetime or w/e unless a new standard comes out), it seems like "std::" or "using std::" should be used instead.  Does anyone disagree?

 

by: evilrixPosted on 2009-08-19 at 23:39:11ID: 25139773

>> A possible solution to that could be either doing a find & replace all on all documents in an IDE
I nearly always use typedefs from the off-set to (a) make code more readable and (b) provide abstraction from the real types. All that would be required is the modification of the typedef.

typedef std::list<int> mylist_t; // I'd name this after what it actually represents to give it semantic meaning

Of course, there is nothing to suggest they'd have identical interfaces so it's probably going to need effort no matter what you do.

 

by: peprPosted on 2009-08-20 at 01:12:55ID: 25140174

It is questionable, whether we are albe to find the anwer here. As far as I know, the C++ committee allowed new features only when it could not be replaced by the existing features (i.e. no new keywords or structures or the core functionality if it can be solved by a library). Namespaces are clearly the core functionality. However, namespaces (generally) can work without 'using ...'. This way, there must had been reasons why they put it there (sorry for my possibly bad English grammar -- my fourth language ;). It could be the case that it was neccessary for other reasons be able to write something like 'list' without neccessity to write 'st::list' to implement say some generic code. Maybe, we did not touch the reason why 'using ...' must be there and we only discuss the case that we 'can' use it and when it is good and when it is bad.

It would be interesting to search for the original reasoning of the 'using namespace ...' or 'using xxx::yyy'. This way we could possibly compare the 'neccessity to use it' with the 'possibility to use it'. We could possibly find that the existence of 'using ...' is some compromise on itself (the related reasons could explain the existence of ADL). This could help to find and explain the 'suggested practice' for a programmer.

 

by: Infinity08Posted on 2009-08-20 at 01:15:25ID: 25140188

>> Well, I did write some code that demonstrated uncaught ambiguity when using ADL but decided against posting it because it was a little contrived (although it could happen in the real world).

I'd still like to see it though ;) If you didn't throw it away already heh.



Basically it comes down to this : follow the company/coding conventions for the project you're working on. If there are none or they don't talk about namespaces, choose wisely between the two options, weighing the advantages against the disadvantages, depending on the specific environment.

When given the choice, I'd still not use the using directive (using namespace std;). But I understand the reasons of the "opposite camp", and they make sense too :)

I can sense this is going to be difficult to close and award points lol.

 

by: evilrixPosted on 2009-08-20 at 01:22:43ID: 25140225

>> I'd still like to see it though ;) If you didn't throw it away already heh.
I did, but it won't be too hard to recreate... I'll post it back here sometime later.

>> I can sense this is going to be difficult to close and award points lol.
Good luck with that... seriously though, I doubt anyone in this thread (all long term experts) are too worried about points so I'm pretty sure just picking a few salient posts that demonstrate the general feel of the thread will be fine by us all (I hope I speak for everyone here :) ).

 

by: Infinity08Posted on 2009-08-20 at 02:25:11ID: 25140522

>> It would be interesting to search for the original reasoning of the 'using namespace ...' or 'using xxx::yyy'.

Here's what Stroustrup says in paragraph 5.2 of "An Overview of the C++ Programming Language" (http://www.research.att.com/~bs/crc.pdf) :

        Repeating a namespace name can be a distraction for both readers and writers. Consequently, it is possible
        to state that names from a particular namespace are available without explicit qualification. For example:

            void f(int max)
            {
                using namespace Mylib;   // make names from Mylib accessible
                Stack<int> s1(max);      // use my stack
                Yourlib::Stack s2(max);  // use your stack
                // ...
            }

So, the original reason for including it in the C++ standard seems to be the exact same reason mentioned in this thread in favor of using the using directive.


Here's another interesting read : "Using Me" by Herb Sutter and Jim Hyslop :

        http://www.ddj.com/cpp/184401782

and the referenced comp.lang.c++.moderated discussion on this exact issue :

        http://groups.google.ca/group/comp.lang.c++.moderated/browse_frm/thread/34f00c3ce3f3f3b7?hl=en&lr=&ie=UTF-8&oe=UTF-8&rnum=65&prev=/groups%3Fq%3Dgroup:comp.lang.c%252B%252B.moderated%2Binsubject:%2522how%2Bto%2Bsay%2522%26hl%3Den%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26start%3D60%26sa%3DN%26filter%3D0

 

by: peprPosted on 2009-08-20 at 03:57:50ID: 25140936

Infinity08: Good source, in my opinion. As Herb Sutter is one of the C++ committee, his "Using Me" from above (http://www.ddj.com/cpp/184401782) could be considered a a reasonable answer (citation):

"A few years back, there was a great dissension and discord in the Usenet group comp.lang.c++ .moderated. This normally meditative group was rocked with discussion on the pros and cons of the using directive [2]. Prophets great and small argued on both sides of the matter. No clear consensus emerged from that debate; indeed, the moderators shut down the discussion because it was generating more heat than light, as the proverb goes.

"My own opinion and recommendation is that namespaces are designed to resolve name clashes, not to prevent them. As such, our coding guidelines tell us to write using directives or declarations to taste, with some restrictions. Thou shalt not allow a using directive or using declaration to appear in a header, nor shalt thou suffer a using directive or using declaration to appear before any #include statements in a file."

Also, the last point was not discussed above, if I remember correctly.

 

by: Infinity08Posted on 2009-08-20 at 04:32:10ID: 25141151

Yep, I know about Herb Sutter, which is why I mentioned it as an interesting viewpoint. It kind of comes down to the same conclusion we came up with ourselves. As long as you know what you're doing, either approach is just fine (for .cpp files). Some will prefer one over the other, and that's fine too.

We all agreed (from the beginning) that in header files, the using directive should never be used. Extending that to before the #includes, is obvious/logical, but indeed worth mentioning.

 

by: ikeworkPosted on 2009-08-20 at 05:02:41ID: 25141351

Thats a nice summary, thanks for the interesting thread Infinity.
And as pepr already said, dont worry about how to reward points.
What about dice or a little side-quest quiz? ;)

 

by: ZoppoPosted on 2009-08-20 at 05:06:54ID: 25141383

@Infinity08: my suggestion about points is to ask moderators to move the question to PAQ and refund the points to you.

 

by: peprPosted on 2009-08-20 at 05:47:53ID: 25141747

Well, knowing enough things, everything is logical ;)  The problem is that we all need the rules of thumb to manage the complexity without neccessity to rethink it again and again.

 

by: evilrixPosted on 2009-08-20 at 06:15:58ID: 25142075

>> And as pepr already said, dont worry about how to reward points.
Did you mean me? {http:#25140225}

 

by: Infinity08Posted on 2009-08-20 at 06:27:43ID: 25142218

I'll gladly spend my points, so there's no need for a refund :) It's just a matter of picking the right set of posts that together form a good sumary of the discussion heh.

Just give me a bit of time to work out how best to do it :) I'll give everyone a last chance to come up with a killer argument, and then I'm closing it :)


@pepr : true. And it's what makes this kind of discussion worthwhile. It makes us all think about an issue, and consider things from different viewpoints, resulting in an enrichment of all participants.

 

by: ikeworkPosted on 2009-08-20 at 06:39:10ID: 25142337

>> >> And as pepr already said, dont worry about how to reward points.
>> Did you mean me? {http:#25140225}

Oops, yes .. sorry rix .. ;)

 

by: Infinity08Posted on 2009-08-22 at 02:10:23ID: 31614747

Thanks to all for your participation. It was a great discussion, and I hope you enjoyed it as much as I did :)

 

by: Infinity08Posted on 2009-08-22 at 02:18:18ID: 25157994

I spent quite a bit of time trying to figure out how to split the points fairly lol. I followed my original intent of assigning points on the basis of merit to the discussion. I hope none feel cheated :)

In any case, I hope you enjoyed this discussion as much as I did. We should do this more often. Whenever someone can think of an interesting topic to discuss, just create a question for it, and we can exchange ideas, and probably learn a lot from each other.

Thank you all !

 

by: Infinity08Posted on 2011-04-06 at 06:40:28ID: 35333170

Heh : the following post made me think of this discussion :

        http://www.experts-exchange.com/Programming/Languages/CPP/Q_26934604.html#a35333032

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...