Is it okay to implement reference counting through composition?

Posted by Billy ONeal on Stack Overflow See other posts from Stack Overflow or by Billy ONeal
Published on 2010-04-15T01:26:48Z Indexed on 2010/04/15 1:33 UTC
Read the original article Hit count: 370

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about reference-counting