在堆上分配内存时防止数组衰减? [英] Preventing array decay when allocating memory on the heap?

查看:108
本文介绍了在堆上分配内存时防止数组衰减?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写int* a = new int[5];然后调用sizeof(a)sizeof(*a),我将无法获得所需的信息,因为该数组已衰减为指针.但是,我想知道是否有一种方法可以做这样的事情:

If I write int* a = new int[5]; and then I call sizeof(a) or sizeof(*a), I don't get the information I want because the array has decayed into a pointer. However, I'm wondering if there's a way we can do something like this:

int[5]* a = new int[5];

我很确定我们能够使用堆栈内存来做到这一点,但是我不确定是否有任何方法可以用于堆内存,因为上面的内容无法编译. 如果没有办法,是否有理由不这样做呢?

I'm pretty sure we're able to do this with stack memory but I'm not sure if there's any way to do it for heap memory, since the above will not compile. And if there isn't a way, is there a reason for not having this as a possibility?

推荐答案

无法在指针中存储此信息.而且没有单独的构造可以让您按照自己的方式进行操作.您的选择是:

There is no way to store this information in the pointer. And there is no separate construct that will let you do this the way you want. Your options are:

  1. 将数组的大小单独存储到数组:const int a_size = 5; int *a = new int[a_size].
  2. 使用C ++构造为您处理此问题:std::vector<int> a(5); a.size()
  1. Store the size of the array separate to the array: const int a_size = 5; int *a = new int[a_size].
  2. Use a C++ construct to handle this for you: std::vector<int> a(5); a.size()

我强烈建议您选择选项2.这不仅是因为它更简单,而且std::vector还提供了更多功能.但是因为RAII样式构造可以为您管理内存,所以您无需记住以后再在内存上调用delete[].您以后也不会意外地在内存上调用delete,因为您可能已经忘记了它是一个数组.

I would highly recommend option 2. Not simply because its easier and std::vector gives more functionality. But because the RAII style construct manages the memory for you meaning you don't need to remember to call delete[] on the memory later. You also can't accidentally call delete on the memory later since you might have forgotten that it is an array.

这篇关于在堆上分配内存时防止数组衰减?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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