PDA

View Full Version : Pointers and QLIst<int*> and stack and heap



mobucl
12th February 2011, 10:49
Hi, this is proberbly a really stupid question but im learning QT and C++ as i write, so i understand the following (which i think is correct):

int k; -> create a variable on the stack with local scope
int *ptr -> create a pointer (i think on the heap??)
ptr = &k -> point to adress of k

Also new is used to put things on the heap:

int *k = new int;

Ok so what does QList<int*> do???? is this also a pointer? what is the difference and whay would i use this rather than QList<int>. I guess it is somethin to do with pointers but i can only find information on *ptr and &variable. Also i see you cant do:

int* k;

Sorry if this is a stupid question but thanks for any help!

Zlatomir
12th February 2011, 11:12
Is something like:
int k; -> create a variable on the stack with local scope
int *ptr -> create a pointer (the pointer itself is on the stack)
ptr = &k -> point to address of k (the pointer is pointing to a stack memory address)

int *ptr0 = new int(10); //the pointer is still on the stack
But we now have an unnamed int (value 10) somewhere on the heap and the only way to access the unnamed integer is with that pointer and if the pointer (ptr0) gets out of scope without calling delete it will cause a memory leak.

Of course there are other techniques that can help with that like other pointer takes ownership for that heap memory, or some sharing mechanisms (when 2 or more objects share some piece of memory) or some reference counting (see smart pointers) when the last pointer to that object delete the object, but this are a little more advanced stuff that you will learn about them as you will continue with Qt.

mobucl
12th February 2011, 12:01
Hi Zlatomir, thanks for the information, that made it mujch clearer.

Please can you tell me what:

QList<int*> name;

Does then? I cant find information about when * is after the type as in this case. And also as i said below i note that you cant do:

int* name

So i guess it is something to do with QLists?

thanks

Matt

Zlatomir
12th February 2011, 13:07
QList<int*> name; name is a QList which contains pointers to int (note that no objects are created now).
If you use it make sure you initialize the pointers, else you will get "seg fault" or "access violation"

And if you allocate memory on the heap, you will need to delete those pointers (the list doesn't do that automatically***)

***for the types that can have parents and have a parent you don't need that since Qt has some memory management for QObjects see parent-child relationship in the documentation.

Added after 37 minutes:


And also as i said below i note that you cant do:
int* name

Yes you can, it's the same as: int *name; //it's a matter of style if you put the '*' closer to the type, or closer to the pointer variable name, the compiler doesn't care.