Difference between QSharedPointer and QSharedDataPointer?
Asked Answered
R

1

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?

Rani answered 6/10, 2010 at 22:59 Comment(0)
M
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).

Monophyletic answered 7/10, 2010 at 0:19 Comment(3)
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?Rani
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.Monophyletic
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.Linlithgow

© 2022 - 2024 — McMap. All rights reserved.