While reading Ruminations on C++ I’ve come upon Obj_trace class used to track constructions of an object by simply making it part of traced object class declaration:
class Foo {
public:
…
Obj_trace xxx;
}
It produces output like:
Object 1 constructed
Object 2 constructed
Object 1 destroyed
Object 3 constructed
This works fine with one class. Now I wonder how to make it work with more classes at the same time, producing output similar to this one:
Foo: Object 1 constructed
Bar: Object 1 constructed
Foo: Object 2 constructed
Closest solution I’ve come across is in this post by Nick Gammon, though I wonder whether there is a way to make it work without need for inheritance, and perhaps 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;
template<typename Outer>
class Obj_trace;
and use it like
Obj_trace<Foo> xxx;
That will also give you a separate count for each object type. Inside Obj_trace
, you can use typeid(Outer)
to get a type_info
with the name of the type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With