PDA

View Full Version : Allocation of object within a function with pointer local on stack



montanaviking
3rd November 2020, 05:34
I'm still an amateur at Qt and C++ so I'm sure I'm missing something obvious here.
I am allocating an object, call it A, on the heap within a function (or method) using a locally-defined pointer. My function passes in A's parent, PA so that A can be deleted automatically when PA is deleted as shown in the example below:

void f(PA,datatoplot)
{
AType *A = new AType(PA,datatoplot); // note that PA is the parent of A, passed to A's constructor and PA is a pointer
.....
..... // more code, but A is not explicitly deleted or deallocated

A->show() // say A is some kind of plot or other widget and we're displaying it here. Repeated calls to f show different plots
}

My question: Will this lead to memory leaks and/or dangling pointers? The pointer A gets deleted from the local stack of f() each time we exit f() but a copy of A is created in RAM every time f() is called. I'm presuming that it doesn't matter if the local pointer to A is lost due to the disposal of the stack of f() when exiting f() because PA retains a copy of each pointer of each copy of A created (one for each call to f()) and when PA is deleted, all the copies of A will also be deleted? If only PA needs to handle the memory management of all the copies of A, does the above lead to problems?
Thanks so much,
Phil

Ginsengelf
3rd November 2020, 07:22
Hi, the parent widget will delete its children, so PA will delete all the new A objects, but only when PA itself gets deleted. So while PA exists you will accumulate AType objects which you cannot access because you did not store a pointer (you could get a pointer by using methods like QObject::findChild, but I try to avoid that if I can).

It would be nicer if you would clean unused AType objects, or (probably better because it avoids the new allocations) you can create it once on the first call, then re-use the AType object from the first call and only use show() and hide().

Ginsengelf