output is the only thing you allocate, so it's the only thing you need to delete from inside func(). BUT this still leaks memory, because the original instance is overwritten when you reassign instance, so that is never deleted
A* instance = new A; delete instance; instance = instance->func(); delete instance;
This would have no leaks
L21 calls new L11 calls new (called by L22) So 2 calls to delete are required to clean up
To answer your question; no Deleting instance results in output being deleted. int number is basically automatically deleted when the function returns, static int x is never deleted, and never created, there's just one x for the entire lifetime of the program
Yes, technically I need to delete 'output' if I want to deallocate it. But also I need it to return from my function.. actually I will be happy if it gets deleted by deleting the 'instance' variable, so the memory leaks will be avoided ....
Why should deleting the object instance delete all data in func?
Are you on Linux? I think you should try ltrace
I thought deleting instance result in deleting on-heap-allocated data too .. that's my guess
It does, but variables in functions are not on-heap
That's an online compiler
What do you mean by "when you reassign instance" ? Like what I did on line 22 here ? https://t.me/thedevs_c/246528
delete will free the memory allocated by new. So in this case yes. As for the static variable,it remains until your program terminates.
Here you said "that is never deleted" but here https://t.me/thedevs_c/246534 you also said deleting instance results in deleting output... So .. ? I'm a bit confused 😬 Will output be deleted by deleting instance?
// this is never deleted A *instance = new A; A *output = new A; instance = output; // output is deleted delete instance;
instance = output; overwrites the original address of instance, and then the original can never be deleted, because you lost the address to it
Oh now I understand A* instance = new A; A* ptr = instance; instance = instance->func(); /* some code */ // GC delete instance; instance = ptr; delete instance; This one also works right ?
Обсуждают сегодня