In Which Situations To Delete A Pointer

后端 未结 5 1937
深忆病人
深忆病人 2021-01-17 10:55

My following question is on memory management. I have for example an int variable not allocated dynamically in a class, let\'s say invar1. And I\'m passing the memory addres

5条回答
  •  不知归路
    2021-01-17 11:23

    Because it has the address of an undynamically allocated int I thought I don't need to delete it.

    Correct.

    Should I delete obj when I'm already deleting objtoclass?

    No.

    Recall that you're not actually deleting pointers; you're using pointers to delete the thing they point to. As such, if you wrote both delete obj and delete objtoclass, because both pointers point to the same object, you'd be deleting that object twice.

    I would caution you that this is a very easy mistake to make with your ex2 class, in which the ownership semantics of that pointed-to object are not entirely clear. You might consider using a smart pointer implementation to remove risk.

提交回复
热议问题