In Which Situations To Delete A Pointer

后端 未结 5 2057
深忆病人
深忆病人 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:21

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

    Well you could but mind that deleting the same object twice is undefined behaviour and should be avoided. This can happen for example if you have two pointers for example pointing at same object, and you delete the original object using one pointer - then you should not delete that memory using another pointer also. In your situation you might as well end up with two pointers pointing to the same object.

    In general, to build a class which manages memory internally (like you do seemingly), isn't trivial and you have to account for things like rule of three, etc.

    Regarding that one should delete dynamically allocated memory you are right. You should not delete memory if it was not allocated dynamically.

    PS. In order to avoid complications like above you can use smart pointers.

提交回复
热议问题