Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make C++ construction trace class take parameter?

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;
like image 661
Mr. Tao Avatar asked Apr 21 '14 00:04

Mr. Tao


1 Answers

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.

like image 93
Ben Voigt Avatar answered Oct 12 '22 08:10

Ben Voigt