简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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