[Solved] QSharedData/QSharedDataPointer: questions on Qt-example

  • I just read the example for "QSharedDataPointer":http://qt-project.org/doc/qt-5/qshareddatapointer.html (it's right there in the documentation). And there are a couple of details I didn't immediately understand - maybe somebody can help. I will just copy the example and add some comments:

    @#include <QSharedData>
    #include <QString>

    class EmployeeData : public QSharedData
    EmployeeData() : id(-1) { } //Why is the QSharedData-constructor not called?
    EmployeeData(const EmployeeData &other)
    : QSharedData(other), id(other.id), name(other.name) { }
    ~EmployeeData() { }

    int id;
    QString name;


    class Employee
    Employee() { d = new EmployeeData; } //memory for d is dynamically allocated but never freed?
    Employee(int id, QString name) {
    d = new EmployeeData;
    Employee(const Employee &other)
    : d (other.d)
    void setId(int id) { d->id = id; }
    void setName(QString name) { d->name = name; }

    int id() const { return d->id; }
    QString name() const { return d->name; }

    QSharedDataPointer<EmployeeData> d;

    Especially the point of d using dynamically allocated memory is bugging me. I could imagine that "QSharedData":http://qt-project.org/doc/qt-5/qshareddata.html deletes itself when appropriate but I didn't find anything about that in the documentation. Hence this looks like a memory leak to me.

    I hope somebody can help me out. :)

  • Possible. Just call destructor on QSharedDataPointer. It should release. You can also check with creating few thousand variables and releasing them. See how it goes.

  • Lifetime Qt Champion


    d is a not a pointer it's in a "container" class that stores the pointer to the allocated QSharedData derived class. So when the Employee object is destroyed, the data will be automatically released if there's no more reference to it.

    @Dheerendra don't call destructors directly, they are not meant to be used like that.

    Hope it helps

  • Thanks a lot. :)

    Do you happen to know anything about the second "problem", too?

  • Lifetime Qt Champion

    Do you mean the constructor ?

    Sure it's called, why do you think it's not ?

  • Because it is not called? Or did I miss some feature of C++ where baseclass constructors are automatically called?

    EDIT: Just to clarify things:
    @class EmployeeData : public QSharedData
    EmployeeData() : id(-1) { }@
    This is an inline method, a constructor that does not call QSharedData() - maybe it's a bug in the documentation, but I wanted to be sure.

  • Lifetime Qt Champion

    AFAIK, base class constructors are automatically called for you if they have no argument(s).

  • Oh, thank you. That is something I didn't know yet.

    I will mark the thread as solved, then. :) (Thanks again!)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.