In our company, just until recently, we were not using namespaces because some compilers could not support them well.
This lead to numerous occurrences of the following mistake:
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);
...
} // calls file_B::~Node() !!!
Each author Node did not know the existence of the other Node, but since he expected that this class name might be reused, he refrained from creating a .hpp file with it.
The compiler silently removes one of the destructors, as their signature matches, and the bug is hard to find, since it may not replicate in different computers.
Once the error had been identified, people gradually became aware of it, and they try to seal the definitions in unnamed namespaces, or avoid inilining the member functions in the class’ body [see below].
-
Question 1: Since you can’t trust that the programmer will always remember to program defensively, is there a tool that can detect these “unintended weak link symbols” ?
By unintended I mean,
Nodeclasses were not defined in .hpp files, and at least one class member doesn’t match between the class definitions… -
Question 2: If we don’t use namespaces, but we do inline every function, is there a possibility that the auto-generated functions (copy-ctor, copy-assignment, destructor) will create the aforementioned “weak link bug” ?
Way 1: enclose in unnamed namespaces
namespace {
class Node {
Data *ptr;
Node() { ptr = new Data; }
~Node() { delete ptr; }
};
}
Way 2: avoid inlining
class Node {
Data *ptr;
Node();
~Node();
};
Node::Node() { ptr = new Data; }
Node::~Node() { delete ptr; }
If your code base is large enough to justify the effort, you could customize an existing compiler to tackle with your issue:
In both cases, it is a effort of several days or weeks, and the most difficult is to understand partly the compiler internal representations (Gimple & Tree for GCC) and organizations (e.g. passes).
I am the main author of MELT and I will be delighted to help you with MELT, so feel free to contact me.