DEV Community

Cover image for Effective C++ Programming: Best Practices and Common Pitfalls

Effective C++ Programming: Best Practices and Common Pitfalls

Itsuki Tatsuya (いつき たつや) on March 04, 2024

As you delve into the world of C++ programming, understanding best practices and avoiding common pitfalls is key to producing efficient, secure, an...
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...

Collapse
 
pauljlucas profile image
Paul J. Lucas

You should (but don't) give examples of everything you mention.