Is it okay to implement reference counting through composition?
- by Billy ONeal
Most common re-usable reference counted objects use private inheritance to implement re-use. I'm not a huge fan of private inheritance, and I'm curious if this is an acceptable way of handling things:
class ReferenceCounter {
std::size_t * referenceCount;
public:
ReferenceCounter()
: referenceCount(NULL) {};
ReferenceCounter(ReferenceCounter& other)
: referenceCount(other.referenceCount) {
if (!referenceCount) {
referenceCount = new std::size_t(1);
other.referenceCount = referenceCount;
} else {
++(*referenceCount);
}
};
ReferenceCounter& operator=(const ReferenceCounter& other) {
ReferenceCounter temp(other);
swap(temp);
return *this;
};
void swap(ReferenceCounter& other) {
std::swap(referenceCount, other.referenceCount);
};
~ReferenceCounter() {
if (referenceCount) {
--(*referenceCount);
if (!*referenceCount)
delete referenceCount;
}
};
operator bool() const {
return referenceCount && (*referenceCount != 0);
};
};
class SomeClientClass {
HANDLE someHandleThingy;
ReferenceCounter objectsStillActive;
public:
SomeClientClass() {
//Construct handle thingy
}
~SomeClientClass() {
if (objectsStillActive)
return;
//Release resources
};
};
or are there subtle problems with this I'm not seeing?