tags:

views:

74

answers:

1

Hi, 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?

+1  A: 

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 http://stackoverflow.com/questions/2491707/memory-management-in-qt, I found this link http://labs.qt.nokia.com/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).

photo_tom
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
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
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