![]() |
Qt: ridiculous behaviour
Hi,
I'm pretty new to Qt development, and I've just encountered something that I wasn't able to figure out for hours. How come that the following code doesn't work: Code:
QNetworkRequest request(QUrl("http://venemo.net/Default.aspx")); Code:
QNetworkRequest request(QUrl("http://venemo.net/Default.aspx")); Can anyone elaborate on this? |
Re: Qt: ridiculous behaviour
The difference in your code is that in one, you create the QNetworkManager on the stack
QNetworkManager m; and in the other you create it on the heap m = new QNetworkManager(); When you create on the stack, at the end of the current closure, the memory will be freed, and the ~QNetworkManager() method called. |
Re: Qt: ridiculous behaviour
It's not exactly the same. In first case the manager object gets automatically deleted when it goes out of scope (that is, when '}' is reached if I remember correctly).
In the second case the manager object (to which the pointer refers to) allocated with "new" never gets deleted unless "delete" is used on it. It results in memory leak if you forget to delete it. |
Re: Qt: ridiculous behaviour
Thanks!
Indeed, those C++ courses were quite long ago. I forgot that the QNetworkManager instance is destroyed after the function call ends, and it really shouldn't be destroyed because it is requred to call back the finished event. I feel so ashamed now... :( |
Re: Qt: ridiculous behaviour
Quote:
i mean, is it only a difference in term of memory allocation?? |
Re: Qt: ridiculous behaviour
Objects on the stack don't need to be deleted.
Code:
// returns dead pointer (obj dies when leaving function) |
Re: Qt: ridiculous behaviour
thanks for reply! what if a pointer(heap allocation) is declared in a method but not returned?? it's not dead, but also out of scope, so not usefull?
i mean: Code:
void function() |
Re: Qt: ridiculous behaviour
Quote:
But QObject's have an exception with the deleting: Every QObject deletes it's children when it is deleted. So always do "new QObject(parent)" when possible, then you don't have to care about memory freeing. |
Re: Qt: ridiculous behaviour
Quote:
And my advice: if you ask yourself if heap or stack should be used, the stack is mostly the better solution. |
Re: Qt: ridiculous behaviour
Quote:
so with this trick i don't need to call explicitly delete on every object but just on "main objects"?! thanks for help! i'm missing java garbage collector :o |
All times are GMT. The time now is 21:22. |
vBulletin® Version 3.8.8