Reference counting trouble
In this problem, the given code does not compile at all. Even though there is not any problem with the code at first glance.
In the given code, a base class for reference-counted objects is implemented
and then used in a small example. To disallow users from bypassing the
reference count by mistake and do an explicit delete on a reference
counted object, the operator delete is overridden as a private member
function for the RefObject class. The mystery here is why the compiler
generates an error when we are trying to do new MyObject, where MyObject
inherits from RefObject. Why is this an error? Can we do something else get
the same behavior?
refcount.cpp
#include <string>
using namespace std;
/**
* Base-class for reference-counted objects. When created,
* the reference count is set to 1. After that, use
* addRef() and release() to alter the internal count.
*/
class RefObject {
public:
RefObject() {
refs = 1;
}
// Add a reference.
void addRef() { refs++; }
// Release our reference.
void release() {
if (--refs == 0)
delete this;
}
private:
// Current number of references to this object.
int refs;
// Let's declare this as private to disallow users of RefObjects to do
// delete refObject!
void operator delete(void *mem) { delete mem; }
};
/**
* Another class we want to be reference counted.
*/
class MyObject : public RefObject {
public:
string data;
};
int main() {
MyObject *o = new MyObject;
o->data = "Hello!";
o->release();
return 0;
}