14

What is the difference between these two types of pointers? As far as I can read, QSharedPointer can handle situation well, so what is the need for QSharedDataPointer?

demonplus
  • 5,036
  • 11
  • 41
  • 56
paul simmons
  • 5,258
  • 11
  • 49
  • 77

1 Answers1

6

From Qt documentation QSharedDataPointer

The QSharedDataPointer class represents a pointer to an implicitly shared object. QSharedDataPointer makes writing your own implicitly shared classes easy. QSharedDataPointer implements thread-safe reference counting, ensuring that adding QSharedDataPointers to your reentrant classes won't make them non-reentrant. Implicit sharing is used by many Qt classes to combine the speed and memory efficiency of pointers with the ease of use of classes. See the Shared Classes page for more information.

Example usage -

 #include <QSharedData>
 #include <QString>

 class EmployeeData : public QSharedData
 {
   public:
     EmployeeData() : id(-1) { }
     EmployeeData(const EmployeeData &other)
         : QSharedData(other), id(other.id), name(other.name) { }
     ~EmployeeData() { }

For QSharedPointer

The QSharedPointer class holds a strong reference to a shared pointer The QSharedPointer is an automatic, shared pointer in C++. It behaves exactly like a normal pointer for normal purposes, including respect for constness. QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it.

>  QSharedPointer<MyObject> obj =
>          QSharedPointer<MyObject>(new MyObject);

So, the QSharedDataPointer is used to make creating implicititly shared classes. Whereas QSharedPointer is a reference counting Smart pointer that points to classes.


EDIT

When reading Memory management in Qt?, I found this link http://blog.qt.io/blog/2009/08/25/count-with-me-how-many-smart-pointer-classes-does-qt-have/. A really excellent discussion of the different smart pointers Qt has (current API has 8).

Checo R
  • 672
  • 10
  • 19
photo_tom
  • 7,162
  • 13
  • 62
  • 115
  • 1
    I think I am missing a point; as far as I can read, we can implement the Employee example with QSharedDataPointer, already with QSharedPointer. What's the catch? – paul simmons Oct 07 '10 at 00:43
  • 5
    QSharedDataPointer is for implementing shallow copying, i.e. sharing data, of a class data's between multiple instances of the class. Reference doc shows the class inheriting QSharedDataPointer. So it is INTERNAL to the class. QSharedPointer is an EXTERNAL to the class and implements a reference counting pointer to a single instance of a class. So it this allows multiple pointers to point to the same class instance. – photo_tom Oct 07 '10 at 00:59
  • 1
    QSharedDataPointer is a nifty way to implement copy-on-write and detaches/copies its object when it is accessed in a non-const way. It has the limitation that the template argument needs to inherit from QSharedData. – Frank Osterfeld Oct 07 '10 at 05:56