質問

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_ptrs but this is for a specific reason.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top