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?
std::shared_ptr. It has this built in.