4

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; }
demonplus
  • 5,613
  • 12
  • 49
  • 68
jcxz
  • 1,226
  • 2
  • 12
  • 25

2 Answers2

4

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.

Dan Milburn
  • 5,600
  • 1
  • 25
  • 18
  • Thanks for the answer, this is basically what I thought, I just wanted to have it confirmed that there is not any hidden catch. – jcxz Mar 13 '13 at 10:19
2

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • 1
    Thanks for your answer and sorry to respond late, I was reading through the faq you linked in (you have my upvote for this). My point was, as Dan mentioned too, that `QSharedData` is basically a base class, which disables assignment operator, but that does not prevent inherited class from defining its own `operator=`, which in turn means, that we only want to prevent the reference count from being copied. And this is what I wanted to have confirmed, that there is nothing unexpected going on. – jcxz Mar 13 '13 at 10:18