简体   繁体   English

数组的C ++内存分配

[英]C++ memory allocation for arrays

Really simple question, but I could not find an answer: are the following 2 expressions equivalent in C++ in terms of memory allocation? 确实很简单的问题,但是我找不到答案:就内存分配而言,以下2个表达式在C ++中是否等效?

wchar_t wide_array[10];
wchar_t* ptr_wide_array = new wchar_t[10];

So I would like to know: do I always have to delete the array no matter how I initialize it? 所以我想知道:无论我如何初始化,都必须删除数组吗? Or can I somehow benefit from scoping and produce arrays on the stack that simply die without explicitly calling delete, as they go out of scope. 或者,我可以从某种程度上受益于范围界定并在堆栈上生成数组,这些数组在超出范围时会死而无需显式调用delete,而不会显式调用。 And of course does it worth using scoping if possible or is it safer to always use delete? 当然,如果可能的话,值得使用作用域定义吗?还是始终使用delete更为安全?

In C/C++, an array readily decays[#] into a pointer to its first element. 在C / C ++中,数组很容易将[#]衰减为指向其第一个元素的指针。 So *wide_array and wide_array[0] are the same thing. 所以*wide_arraywide_array[0]是同一件事。 In fact, wide_array[i] is actually defined as (or, if you like, is syntactic sugar for) (wide_array + i) . 实际上, wide_array[i]实际上定义为(wide_array + i) (或者,如果您愿意,则是语法糖(wide_array + i) So much so that i[wide_array] means the same thing as wide_array[i] , which is an amusing way to obfuscate C/C++ code (but never ever do it!). 如此之多以至于i[wide_array]wide_array[i] i[wide_array]含义相同,这是使C / C ++代码模糊化的一种有趣的方式(但从来没有这样做!)。

So your second example can also be referenced as ptr_wide_array[i] . 因此,您的第二个示例也可以引用为ptr_wide_array[i]

That's as far as syntax goes. 就语法而言。 Now, as to what goes on under the hood: 现在,关于幕后情况:

The difference between your two examples is that the first is allocated on the stack, the second on the heap . 您的两个示例之间的区别在于, 第一个示例分配在堆栈上,第二个分配在堆上 This implies that the first one will be automatically deallocated once it goes out of scope, but the second won't be deallocated until delete[] ptr_wide_array is called (or on another pointer which was copied from ptr_wide_array ). 这意味着第一个指针将在超出范围后自动释放,但是第二个指针将在调用delete[] ptr_wide_array (或从ptr_wide_array复制的另一个指针)之前被释放。 This runs a serious risk of memory leaks, especially if you start using exceptions. 这会带来严重的内存泄漏风险,尤其是在您开始使用异常的情况下。 In general, don't use a raw new in C/C++. 通常,不要在C / C ++中使用原始的new Use containers such as std::vector , and smart pointers . 使用容器,例如std::vector智能指针

[#] See this SO question for an explanation of how arrays and pointers are related and how arrays "decay" to pointers. [#]请参见此SO问题 ,以获取有关数组和指针如何关联以及数组如何“衰减”到指针的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM