If I delete a class, are its member variables automatically deleted?

前端 未结 8 534
故里飘歌
故里飘歌 2020-12-13 06:28

I have been researching, and nothing relevant has come up, so I came here.

I am trying to avoid memory leaks, so I am wondering:

Say I have class MyCla

8条回答
  •  囚心锁ツ
    2020-12-13 07:18

    The rule is very simple: every object created with new must be destroyed exactly once with delete; every array created with new[] must be destroyed exactly once with delete[]; everything else must not be deleted. So your code is correct; you are deleting mc after creating it with new, and not deleting the members which were not created with new.

    Applying the rule can be quite tricky when the program flow gets complicated (especially when exceptions are involved); for that reason, it is much better not to delete objects yourself, but to immediately use the result of new to initialise a smart pointer to manage the object for you.

提交回复
热议问题