1

Possible Duplicate:
Using std Namespace

I was just wondering if there was some reason to include std:: in some operations, like std::sort() for example. Is it because of possible overloading?

Community
  • 1
  • 1
  • 1
    Because you don't want naming conflicts and to drag the entire `std` namespace into your code. Also this is a duplicate. – Rapptz Feb 03 '13 at 04:37
  • You use it when you want things in the `std` namespace to work, and not use it when you don't. – Andrei Tita Feb 03 '13 at 04:38
  • When someone sees your code and it has `std` in it, for example `std::string`, they would know that it belongs to the standard library. Whereas if someone saw `string` they wouldn't really know if it's a custom class you made or not. At least for me. – Rapptz Feb 03 '13 at 04:40

1 Answers1

1

Apart from the usually well known reasons of polluting the current namespace with unnecessary symbol names and readability there is a subtle another reasoning.

Consider the example of std::swap,it is an standard library algorithm to swap two values. With Koenig algorithm/ADL one would have to be cautious while using this algorithm because:

std::swap(obj1,obj2);    

may not show the same behavior as:

using std::swap;
swap(obj1, obj2);

With ADL, which version of swap function gets called would depend on the namespace of the arguments passed to it.
If there exists an namespace A and if A::obj1, A::obj2 & A::swap() exist then the second example will result in a call to A::swap() which might not be what the user wanted.

Further, if for some reason both:
A::swap(A::MyClass&, A::MyClass&) and std::swap(A::MyClass&, A::MyClass&) are defined, then the first example will call std::swap(A::MyClass&, A::MyClass&) but the second will not compile because swap(obj1, obj2) would be ambiguous.

Alok Save
  • 202,538
  • 53
  • 430
  • 533