0

If I've understood Raymond Chen correctly, this is dangerous, but I can't work out exactly why. http://gotw.ca/publications/migrating_to_namespaces.htm

To be clear, this is not about global namespace pollution due to headers injecting entire namespaces into the global scope, and it's notabout the general case of using namespace xyzzy; which some regard as harmful however it's used.

mymodule.h

#include <string>

// using namespace std;  -- this would be dangerous, and we should never do it

namespace MyModule
{
  using namespace std;  // but, why is this dangerous?

  string foo();
}

mymodule.cpp

#include "mymodule.h"

namespace MyModule
{
  using namespace std;

  string foo() 
  {
    return "bar";
  } 
}
Roddy
  • 66,617
  • 42
  • 165
  • 277
  • 1
    The Guru of the Week article is about migrating from pre-standard C++ without namespace `std` - or any namespace - (and where standard headers had an `.h` suffix), to standard C++ with namespace `std` and standard header name. That was a thing requiring caution. The situation you describe is not too comparable and I don't see why you think the conclusion translate well. – StoryTeller - Unslander Monica Mar 21 '23 at 17:03
  • 1
    And at the risk of shameless self-promotion, I believe this [Q&A](https://stackoverflow.com/q/46168188/817643) covers similar ground to the situation you laid out in your snippet. – StoryTeller - Unslander Monica Mar 21 '23 at 17:05
  • The danger is the using directive is pulling in anything that happens to be in `std` — *at that point in the translation unit* — into `MyModule`. If someone includes a standard header file, then includes `mymodule.h` it'd be easy for `std::foo` to collide with `string foo()`. Or some future C++ standard that adds a new colliding symbol. To prevent that kind of contamination just have `namespace MyModule { namespace Secret { using namespace std; } }` and then access them by `Secret::string`. – Eljay Mar 21 '23 at 17:11
  • @StoryTeller-UnslanderMonica - that's close enough to call a duplicate. Thanks. – Roddy Mar 21 '23 at 17:15

0 Answers0