Sobes.tech
Junior — Middle

Explain the working principle of the shared pointer in Qt and its advantages.

sobes.tech AI

Answer from AI

Shared pointer (smart pointer with shared ownership) in Qt is implemented through the QSharedPointer class. It manages the lifetime of the object it points to using reference counting.

Working principle:

  • When creating a QSharedPointer, it starts tracking the number of references to the object.
  • When copying the pointer, the counter increases.
  • When destroying the pointer, the counter decreases.
  • When the counter reaches zero, the object is automatically deleted.

Advantages:

  • Automatic memory management: no need to manually call delete, reducing the risk of leaks.
  • Safety: prevents double deletion and use of dangling pointers.
  • Convenience: simplifies passing objects between parts of a program.

Example of usage:

#include <QSharedPointer>
#include <QDebug>

class MyClass {
public:
    MyClass() { qDebug() << "Object created"; }
    ~MyClass() { qDebug() << "Object deleted"; }
};

int main() {
    QSharedPointer<MyClass> ptr1(new MyClass());
    {
        QSharedPointer<MyClass> ptr2 = ptr1; // reference count increases
    } // ptr2 is destroyed, reference count decreases
    // object is still alive because ptr1 holds a reference
}
// when main exits, ptr1 is destroyed, and the object is deleted automatically

Thus, QSharedPointer helps safely and efficiently manage dynamic memory in Qt applications.