PDA

View Full Version : Qt smart pointer dilema



sajis997
3rd December 2014, 16:21
Hi Forum,

Suppose that i define the following class as the subclass of QObject for smarter memory management:



class Shader : public QObject
{
Q_OBJECT

.....................

.....................
};


Then inside the another class definition i declare a pointer of the above type (composite pattern) as follows:



Shader *shade;


And inside the source of the class definition i allocate memory on the heap. Just because i inherited from QObject , will the memory pointed by shade be de-allocated by Qt ?

If this is so , then what is the point of having the following declaration instead?:



QPointer<Shader> shade;


or



QSharedPointer<Shader> shade;



or



QScopedPointer<Shader> shade;



There are few more in the documentation. Lets understand the above first.

Some explanation with code snippet would be very helpful.

Thanks

wysota
3rd December 2014, 18:13
Just because i inherited from QObject , will the memory pointed by shade be de-allocated by Qt ?
It will be deallocated provided that the object being deleted is set as the parent of the Shader instance. However if you allocate memory in Shader itself without setting Shader as the parent object, you will have to free that allocated memory in the destructor (or elsewhere).


class Shader : public QObject {
Q_OBJECT
public:
Shader(QObject *parent = 0) : QObject(parent) {
o1 = new QObject(this);
o2 = new QObject;
}
~Shader() { qDebug() << "Deleting" << objectName(); }
private:
QObject *o1;
QObject *o2;
};

void someFun() {
QObject p; // allocated on the stack, will be deleted when the function returns
Shader *shader = new Shader(&p);
shader->setObjectName("Shader1");
Shader *shader2 = new Shader; // no parent set
shader2->setObjectName("Shader2");
}

Shader1 will be deleted, Shader2 will not. Following the same rule "o1" will be deleted, "o2" will not.

anda_skoa
4th December 2014, 07:20
Also, in the above usages of smart pointers:

QPointer does not delete the object, its purpose is to track the life cycle of a QObject based instance, i.e. reset itself to 0 if something deletes the object it points to.

Cheers,
_

sajis997
4th December 2014, 18:25
Which type of qt pointer will delete the object as well once goes out of scope or when the application terminates abruptly ?

wysota
4th December 2014, 20:03
When the application terminates then it terminates, nothing will delete it.

ChrisW67
4th December 2014, 20:12
QScopedPointer or QSharedPointer depending on your desired usage. These are close analogues of std::auto_ptr and std::shared_ptr

Which destructors get called in the event of abnormal termination of a C++ program is dependent on a number of factors. All memory allocated to a program will typically be reclaimed by the operating system but other cleanup may not occur.