PDA

View Full Version : (SOLVED) Members of a class should be allocated on heap or stack?



giowck
28th November 2009, 21:30
I didn't find a good answer on the net...

Should i allocate members of a class on heap or stack?



class MyClass
{
public:
MyClass();

private:
QString *heap;
QString stack;
int i, j, k;
AnotherClass anotherclass; // or *anotherclass?
}


When should i use heap allocation?

Lykurg
28th November 2009, 21:39
Should i allocate members of a class on heap or stack?

It depends... But normal is to create basic types at the stack. Is is also true for implicitly shared Qt classes.

All other classes you should normally create on the heap. This is also true for classes which inherits QObject.

giowck
28th November 2009, 22:02
It depends... But normal is to create basic types at the stack. Is is also true for implicitly shared Qt classes.

All other classes you should normally create on the heap. This is also true for classes which inherits QObject.

So, for example: int, short, double... on the stack
QWidget, QMenu... on the heap

Right?

Since, quint64 is a typedef int long long, i should put it on the stack, right?

And where to allocate QStrings, QStriglists...? They are kids of QObject...

Lykurg
28th November 2009, 22:05
So, for example: int, short, double... on the stack
QWidget, QMenu... on the heap

Right?

Since, quint64 is a typedef int long long, i should put it on the stack, right?

Right, but for example if you want only show a dialog and destroy it right afterwards you would normally create it on the stack.

function()
{
MyDialog d;
d.exec();
}
But that's an exeption.


And where to allocate QStrings, QStriglists...? They are kids of QObject...
On the stack, because are not childs of QObject...

giowck
28th November 2009, 22:42
yeah, now i get it! They aren't QObjects!! Thanks for your answer :)

Cause i saw QString allocated on the stack in lastfm src code...

But now i checked it...

BTW thanks for the exception (function() on stack)

Solved!

agnus
29th November 2009, 15:09
class MyClass {
QString *heap;
QString stack;
}

Just a note:
MyClass * myClass = new MyClass;

myClass.stack won't be on the stack but on the heap just like the rest of the class. Defining class members as values makes them "embeded" to the object memory.