DEV Community

Discussion on: Effective C++ Programming: Best Practices and Common Pitfalls

Collapse
 
tandrieu profile image
Thibaut Andrieu • Edited

for 4) Avoid Global Use of using namespace

I would say "Never ever use using namespace in a header file".
using namespace in .cpp file is not that bad. But using it in header will contaminate all the file that include, directly or indirectly, this header. Ex (based on true story):

CustomMemoryManager.h

namespace CustomMemoryManager
{
   void* alloc();
   void free(void*)
}
Enter fullscreen mode Exit fullscreen mode

SomeFile.h

#include <CustomMemoryManager.h>
using namepace CustomMemoryManager;
...
Enter fullscreen mode Exit fullscreen mode

SomeOtherFile.h

#include <SomeFile.h>
Enter fullscreen mode Exit fullscreen mode

AgainAnotherFile.h

#include <SomeOtherFile.h>
Enter fullscreen mode Exit fullscreen mode

AndYetAnotherFile.cpp

#include <AgainAnotherFile.h>

void* ptr = std::malloc(...);

// [hundreds of line later]

free(ptr); // Oups... It build, maybe it even run, but it's actually CustomMemoryManager::free() which is called...
Enter fullscreen mode Exit fullscreen mode

And then, good luck to find the leak...