jcxz
jcxz

Reputation: 1324

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; }

Upvotes: 4

Views: 450

Answers (2)

Dan Milburn
Dan Milburn

Reputation: 5718

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.

Upvotes: 4

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158449

No it would be a bad thing, if it is doing reference counting it needs to do book-keeping and just having it return this would mean there are copies of QSharedData unaccounted for. this example from the C++faq shows basically what kind of book-keeping is needed for operator = in a reference counted object.

Upvotes: 2

Related Questions