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) {
if (!*referenceCount)
delete referenceCount;
else
--(*referenceCount);
}
};
operator bool() const {
return referenceCount && (*referenceCount != 0);
};
};
class SomeClientClass {
HANDLE someHandleThingy;
ReferenceCounter objectsStillActive;
public:
SomeClientClass() {
someHandleThingy = RegCreateKeyEx(...);
}
~SomeClientClass() {
if (objectsStillActive)
return;
RegCloseKey(someHandleThingy);
};
};
or are there subtle problems with this I'm not seeing?
EDIT
I'm not super duper concerned with this particular implementation (it probably has bugs -- I'm going to spend some time looking at shared_ptr's innards before using something like this in production code) -- I'm just concerned if in general there is a specific reason reusable reference counting goodies always seem to be implemented using inheritance rather than composition.