数组的C ++内存分配 [英] C++ memory allocation for arrays

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

问题描述

真的很简单的问题,但我找不到答案:在内存分配方面,以下2个表达式在C ++中是否等同?

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

所以我想知道:我总是需要删除数组, ?或者我可以从某种方式受益于范围和产生堆栈上的数组,只是死而不显式调用删除,因为他们超出范围。

解决方案

在C / C ++中,一个数组容易衰减[#]为指向其第一个元素的指针。因此, * wide_array wide_array [0] 是同样的东西。事实上, wide_array [i] 实际上定义为(或者,如果你喜欢,是语法糖)(wide_array + i)。这么多,使得 i [wide_array] 意味着与 wide_array [i] 相同的东西,这是一个有趣的方式因此,你的第二个例子也可以被引用为 ptr_wide_array [i]

code>。



这就是语法。现在,至于底下发生了什么:



你的两个例子的区别是第一个在堆栈上分配,第二个在堆上。这意味着一旦超出范围,第一个将被自动释放,但是第二个不会被释放,直到 delete [] ptr_wide_array 被调用(或在另一个指针它是从 ptr_wide_array 中复制的)。这会导致内存泄漏的严重风险,特别是如果您开始使用异常。一般来说,不要在C / C ++中使用raw new 。使用 std :: vector 智能指针



[#]请参阅这个问题解释数组和指针如何相关,以及数组如何衰减到指针。 >

Really simple question, but I could not find an answer: are the following 2 expressions equivalent in C++ in terms of memory allocation?

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. And of course does it worth using scoping if possible or is it safer to always use delete?

解决方案

In C/C++, an array readily decays[#] into a pointer to its first element. So *wide_array and wide_array[0] are the same thing. In fact, wide_array[i] is actually defined as (or, if you like, is syntactic sugar for) (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!).

So your second example can also be referenced as 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). 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++. Use containers such as std::vector, and smart pointers.

[#] See this SO question for an explanation of how arrays and pointers are related and how arrays "decay" to pointers.

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

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