c++qtqshareddata

QSharedData and operator=


Recently I wanted to implement implicit sharing functionality like Qt does with its QSharedData and QSharedDataPointer classes, so I took a look at their sources and in the place of QSharedData I found these three lines:

private:
    // using the assignment operator would lead to corruption in the ref-counting
    QSharedData &operator=(const QSharedData &);

However I don't understand how could operator= break reference counting.

If I just did not make it private and left its implementation empty, wouldn't it serve the same purpose ?

i.e. if I wrote simply this:

    public:
    QSharedData &operator=(const QSharedData & ) { return *this; }

Solution

  • The whole purpose of QSharedData is to maintain a reference count. If you assign one to another, what should happen to the reference count on each side? As you have correctly determined: nothing. It simply makes no sense to assign one QSharedData to another, and therefore the sensible course of action is to prevent it at compile time.