Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between QSharedPointer and QSharedDataPointer?

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?

like image 204
paul simmons Avatar asked Oct 06 '10 22:10

paul simmons


1 Answers

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).

like image 162
photo_tom Avatar answered Sep 19 '22 19:09

photo_tom