When reading Ruminations in C ++, I came across the Obj_trace class used to track object constructions by simply making it part of the class declaration of the traced object:
class Foo {
public:
…
Obj_trace xxx;
}
It produces output, for example:
Object 1 constructed
Object 2 constructed
Object 1 destroyed
Object 3 constructed
This works great with one class. Now I wonder how to make it work with a large number of classes at the same time, producing output similar to this:
Foo: Object 1 constructed
Bar: Object 1 constructed
Foo: Object 2 constructed
The closest solution I came across is in this post by Nick Gammon, although I am wondering if there is a way to make it work without the need for inheritance, and possibly with descriptions longer than 1 char.
class Obj_trace {
static int count;
int ct;
public:
Obj_trace() : ct(++count) {
cout << "Object " << ct << " constructed" << endl;
}
~Obj_trace() {
cout << "Object " << ct << " destroyed" << endl;
}
Obj_trace(const Obj_trace & ) : ct(++count) {
cout << "Object " << ct << " copy-constructed" << endl;
}
Obj_trace( Obj_trace && ) : ct(++count) {
cout << "Object " << ct << " move-constructed" << endl;
}
Obj_trace & operator =( const Obj_trace & ) {
cout << "Object " << ct << " copy op =" << endl;
return *this;
}
Obj_trace & operator =( Obj_trace && ) {
cout << "Object " << ct << " move op =" << endl;
return *this;
}
};
int Obj_trace::count = 0;