The question is not whether m
should be deleted, but whether what it points to should be. If you are iterating over a container whose elements are pointers and require deletion at that point in time, you may do delete m;
. m
itself doesn't need to be deleted as its being created on the stack, there's no use of new
in creating the actual pointer, so there is no need to call delete
.
Do I need to delete the pointer in the loop here? [duplicate]
Question
If I have something like this:
for(MyClass* m : a_container){
//
//Do something with m
//
//delete m; ?
}
//delete m; ?
Do I need to delete m
within each loop iteration, or just at the end because the same pointer is being re-used?
NB: I know I should use shared_ptr
s but this is for a specific reason.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow