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

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

问题描述

真的很简单的问题,但我无法找到答案:有以下几种内存分配方面2 EX pressions相当于C ++

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?

推荐答案

在C / C ++中,数组容易衰变[#]成一个指向它的第一个元素。因此, * wide_array wide_array [0] 是一样的。事实上, wide_array [I] 实际上是定义为(或者,如果你喜欢,是语法糖)(wide_array + I)。正因如此, I [wide_array] 意味着同样的事情 wide_array [I] ,这是一个有趣的方式来模糊C / C ++ code(但从来没有做到这一点!)。

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!).

所以你的第二个例子也可以为 ptr_wide_array引用[I]

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:

的两个例子之间的差异是href=\"http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap\">第一被分配在该。这意味着第一个将一旦它超出范围自动释放,但第二个将不被释放,直到删除[] ptr_wide_array 叫(或另一指针这是从 ptr_wide_array 复制)。这将运行内存泄漏的严重风险,特别是当你开始使用异常。一般情况下,不要使用原始用C / C ++。使用的容器,如的std ::矢量和<一个href=\"http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one\">smart指针。

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天全站免登陆