Montoya
Montoya

Reputation: 3049

c++ - Reference Counting garbage collection

Consider a simple class:

class MyInt {
public:
    MyInt();

    MyInt(const char *num);
};

I want to intergrate reference counting design pattern in to the class, which means i need to keep track of how much pointers point to an instance of this class. I need to implement it in this class only or create a different class and inherit it.

Given this example code i want to clear any allocated memory of the program:

int main() {
    MyInt*a = new MyInt("10");
    a = new MyInt("20");
    delete a;
    return 0;
}

My Tries

I tried operator oveloading of '=' and adding referenceCount member:

MyInt &MyInt::operator=(const MyInt* right) {
    MyInt*left = this;
    *this = right;
    left->referenceCount -= 1;
    if (left->referenceCount == 0) {
        delete (left);
    }
    return *this;
}

But this does not work because we assign pointer of the class to another pointer.

Also tried to override the new and delete operators but can't seem to make it work and keep track of the number of pointer to an instance.

As it seems i need to implement four things: copy constructor, operator new, operator delete and operator =.

How can i effectivly keep track of the pointers and clear unpointed memory automaticly?

Upvotes: 2

Views: 627

Answers (2)

François Andrieux
François Andrieux

Reputation: 29013

a is a pointer, so assigning to a will not involve MyInt::opterator= in any way. There is no way to detect when a pointer to T is assigned to by overloading T's operators. To do this, you would need to design a class type that behaves like a pointer. Then you could properly track when the pointer might leak an object and properly delete it. Fortunately for you, the standard library already provides this class. It's std::shared_ptr. Here is your example modified to use std::shared_ptr :

#include <memory>

struct InfInt {
    InfInt(const char *) {}
};

int main() 
{
    auto a = std::make_shared<InfInt>("10");
    a = std::make_shared<InfInt>("20"); // the previous `a` is deleted

    // The object pointed to by `a` is automatically deleted when 
    //  the last reference to it goes out of scope
    return 0;   
}

Upvotes: 1

gsamaras
gsamaras

Reputation: 73366

std::shared_ptr does exactly this. From the ref:

Manages the storage of a pointer, providing a limited garbage-collection facility, possibly sharing that management with other objects. [...] Once all shared_ptr objects that share ownership over a pointer have released this ownership, the managed object is deleted.

so I suggest you use this instead.

Upvotes: 2

Related Questions