Why doesn't deleting my pointer delete my pointer?

前端 未结 8 1621
悲哀的现实
悲哀的现实 2021-02-13 04:22

So to understand new/delete better (really to prove to myself with small examples why virtual destructors are needed for interfaces), I want to understand memory leaks, so that

8条回答
  •  爱一瞬间的悲伤
    2021-02-13 04:57

    I must be doing something very simple very wrong.

    You're absolutely right. Your code is doing something very simple very wrong, and you've paid the ultimate price - not seeing any negative results. Sometimes, you do things wrong, and nothing bad happens. This is the worst possible outcome, because you may not realize your code is wrong, and you'll continue to use it, until one day your code breaks unexpectedly, and you'll have no idea where or how because it's always worked before. It'll break somewhere completely irrelevant to the actual part that's wrong, and you'll spend hours trying to track it down and figure out why it's broken.

    When you do things wrong, it's undefined behavior. That means anything can happen. At best, your code crashes and segfaults and blinking lights come on saying "YOU'RE USING FREED MEMORY" and everything is very clear. At worst, demons fly out of your nose. But just above that, the second worst possible outcome is that everything appears to work as you intended it to.

提交回复
热议问题