valbu17
valbu17

Reputation: 4124

C++ managing the dynamic allocation of your objects

I am trying to implement my own class Alloc which will help in the dynamic allocation of objects..

I want to keep track of the number of allocated objects in my program. So, each time a new instance of an object is allocated, the counter increments by one and decrements when an object is destroyed. When my program shuts down, if the counter is not at zero, the object prints an error message to the screen and has the program hang until the user hits enter..

This is what I have so far.. I hope you guys can help me to implement this..

class Alloc{
static int counter;
public:
Alloc(){ counter++; };
Alloc(int *d, static int size, const Alloc& c){

    d=(int *) malloc(size*sizeof(int));;
    //d=new int[size];
    Alloc *my_alloc;
    //my_alloc = new Alloc[size];                //note that the type is a Myclass pointer
    for(int i=0; i<size; i++){
        my_alloc[i] = new Alloc[size];
    }
    //for(int i=0; i < size; i++){
    //    d[i]=c.d[i];
    //}
}
~Alloc(){ counter--; }
};

I know a lot is missing so, I will appreciate help and fixing mistakes too.. Thanks!!!

Upvotes: 0

Views: 122

Answers (2)

Ali Kazmi
Ali Kazmi

Reputation: 1458

the track of number of instances of class say Alloc can also be kept as

class Alloc
{
    Public:
    static int Coounter; // object counter

//  Constructor

    Alloc(){
    Counter++;}

//  Destructor

    ~Alloc()
    {
    Counter--;
    }


};

Simple, easy to use and maintainable

Upvotes: 2

Tristan Brindle
Tristan Brindle

Reputation: 16864

d=(int *) malloc(size*sizeof(int));;
d=new int[size];

The second line here is overwriting the d pointer with a second allocation, so the memory allocated by malloc is being lost!

If you really want to do it this way you need to use placement new, i.e. something like

d=(int *) malloc(size*sizeof(int));;
e=new (d) int[size];

though the details are quite tricky to get right.


To just count the number of objects in your programme though, there is a much easier option. Implement a templated "mixin" which contains a static counter for each type. Something like

    template <typename T>
    struct countable
    {
        countable() { _count++; }
        countable(const countable&) { _count++; }
        ~countable() { _count--; }
        static int get_count() { return _count; }
    private:
        static int _count;
    };

and then having your objects inherit from this, as in

    class MyClass : countable<MyClass>
    {
        // whatever
    };

It's simple, and easy to turn into a no-op for release builds.

Upvotes: 2

Related Questions