In our company, until recently, we did not use namespaces because some compilers could not support them well.
This leads to numerous cases of the following error:
file_A.cpp
class Node { Data *ptr; Node() { ptr = new Data; } ~Node() { delete ptr; } };
file_B.cpp
class Node { vector<int> v; Point *pt; Node(int x,int y) { pt = new Point(x,y); v.push_back(0); } ~Node() { delete pt; } }; void foo() { Node n(10,10); ... }
Each Node
author was unaware of the existence of another Node
, but since he expected that this class name could be reused, he refrained from creating an .hpp file with it.
The compiler silently deletes one of the destructors, since their signature matches, and the error is difficult to find, because it cannot be replicated on different computers.
As soon as the error was identified, people gradually learned about it, and they will try to seal the definitions in unnamed namespaces or to avoid including member functions in the body of the class [see below].
Question 1:. Since you cannot trust that the programmer will always remember that the program is protected, is there a tool that can detect these “unintended weak link characters”?
Unintentionally, I mean that Node
classes have not been defined in .hpp files, and at least one member of the class does not match between class definitions ...
Question 2: If we do not use namespaces, but we embed each function, is it likely that the automatically generated functions (copy-ctor, copy-assign, destructor) will create the aforementioned "weak link error"?
Method 1: enclose in unnamed namespaces
namespace { class Node { Data *ptr; Node() { ptr = new Data; } ~Node() { delete ptr; } }; }
Method 2: avoid embedding
class Node { Data *ptr; Node(); ~Node(); }; Node::Node() { ptr = new Data; } Node::~Node() { delete ptr; }
source share