C ++-使用"new"在堆上分配内存 [英] C++ - Allocating memory on heap using "new"

查看:167
本文介绍了C ++-使用"new"在堆上分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下说法:

int *x = new int;

在这种情况下,我已经在堆上动态分配了内存.换句话说,我现在有一个reserved对象的reserved内存地址.

In this case, I have allocated memory on the heap dynamically. In other words, I now have a reserved memory address for an int object.

接着说,我做了以下事情:

Say after that that I made the following:

delete x;

这意味着我freed up堆上的内存地址.

Which means that I freed up the memory address on the heap.

说完之后,我再次执行以下操作:

Say after that I did the following again:

int *x = new int;

x会指向它在删除之前指向堆的相同旧内存地址吗?

Will x point to the same old memory address it pointed to at the heap before it was deleted?

如果我在delete之前这样做:

x = NULL;

然后,这样做:

int *x = new int;

x会指向堆上的一个内存地址吗?其他而不是旧地址?

Will x point to a a memory address on the heap other than the old one?

谢谢.

推荐答案

在第一种情况下,您可能再次获得相同的内存块,但是不确定.

In the first case, you might get the same block of memory again, but there's no certainty of it.

在第二种情况下,由于尚未释放内存,因此几乎可以肯定的是,您将在不同的地址获得不同的内存块.有C ++的垃圾收集器.如果您使用了其中之一,则可以想象,垃圾收集器将在您使指针为NULL的时间(因此您不再有权访问先前分配的内存块)与再次请求分配之间运行.在这种情况下,您可能会再次获得相同的内存块.当然,如果没有垃圾收集器,您只会泄漏内存,因此无论如何您都无法做到这一点.

In the second case, since you haven't freed the memory, there's a near-certainty that you'll get a different block of memory at a different address. There are garbage collectors of C++. If you used one of these, it's conceivable that the garbage collector would run between the time you NULLed out the pointer (so you no longer had access to the previously-allocated memory block) and asking for an allocation again. In such a case, you could get the same memory block again. Of course, without a garbage collector, you're just leaking memory, so you don't way to do this in any case.

这篇关于C ++-使用"new"在堆上分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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