为什么不删除我的指针删除我的指针? [英] Why doesn't deleting my pointer delete my pointer?

查看:195
本文介绍了为什么不删除我的指针删除我的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以要更好地了解新的/删除(真的要证明自己与小例子为什么虚拟析构函数是需要的接口),我想了解内存泄漏,让我可能生活在恐惧他们。但我很难得到我的泄漏,可以这么说;

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 I may live in fear of them. But I am having a hard time getting my leak on, so to speak; actually, I am have a hard time with new/delete too.

这是我最简单的版本:

int* P1 = new int(43);

cout<<"P1 = "<<P1<<endl;
cout<<"*P1 = "<<*P1<<endl;

delete P1;

cout<<"P1 = "<<P1<<endl;
cout<<"*P1 = "<<*P1<<endl;

打印:

P1 = 0xcc0340
*P1 = 43
P1 = 0xcc0340
*P1 = 43

我有一个更复杂的内部类,但这个例子说明了我的失败。我认为delete需要一个指针,释放它的内存,从而使指针或至少它指向的指针无效?我必须做一些非常简单的错误。

I had something more complicated inside of a class, but this example illustrates my fail. I thought delete takes a pointer and frees it's memory, thereby invalidating the pointer or at least what it points to? I must be doing something very simple very wrong.

推荐答案

您正在造成未定义的行为。这意味着任何事情都可能发生。因为事情确实发生了,一切都如记录所示。 (有时某事看起来非常类似于你可能错误地期望的其他事情。完全正确地你想要实现的是可能允许的未定义的行为的实例之一。)

You are causing undefined behaviour. This means that anything can happen. Since something did indeed happen, everything behaves as documented. (Sometimes "something" looks very similar to something else that you might erroneously expect. Doing exactly what you think you were trying to achieve is one of the possible allowed instances of "undefined behaviour".)

注意,内存泄漏与你想要做的相反 - 在内存泄漏时你忘记释放内存,而你已经释放了内存并且正在访问无效的内存。

Note also that a "memory leak" is sort of the opposite of what you're trying to do - in a memory leak you forget to free memory, whereas you already freed the memory and are now accessing invalid memory.

这是一个真正的内存泄漏,也不会导致未定义的行为 - 不要混淆坏但正确与不正确编程!

Here's a real memory leak, which also does not cause undefined behaviour -- don't confuse "bad but correct" with "incorrect" programming!

int * factorial(int * n)
{
  if (*n == 0) return new int(1);
  else return new int(*n * *factorial(*n - 1));
}

这篇关于为什么不删除我的指针删除我的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆