Can I count links through a composition?

The most common reusable link reference objects use private inheritance to implement reuse. I'm not a big 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 any subtle issues with this I don't see?

EDIT
I'm not the super-duper associated with this particular implementation (it probably has errors - I'm going to spend some time looking at the shared properties of shared_ptr before using something like this in production code). It just bothers me, is the specific reason for reusing references to counting goods always seems to be implemented using inheritance rather than composition.

+3
3

, . , , . ( HANDLE.)

HANDLE - , POD. T*.

, -, delete, , . , smart_ptr , .

+3

, . . , / . , . , . boost::intrusive?

0

HANDLE HANDLE... shared_ptr.

, , ReferenceCounter HANDLE... , , (arg).

The only valid reason for using private inheritance Empty Base Optimization, all other cases can be considered with a composition that is much better in terms of combination, so it is unlikely that they had good reasons for this, it is more likely that they did it because of falsity or laziness.

0
source

Source: https://habr.com/ru/post/1741197/


All Articles