Reallocating memory of a C++ array. [duplicate]

做~自己de王妃 提交于 2020-01-13 13:06:25

问题


Possible Duplicate:
How do you realloc in C++?

I know that C++ arrays can be reallocated (expanded) using realloc() if memory has been allocated via malloc() or calloc(). My question is, how can I expand an array in C++ whose memory has been allocated via the new operator?


回答1:


You can't - that's why in C++ you use std::vector<>.

If you wanted to do this, you'd have to allocate a new array (via new), then copy the old items across (std::copy for example), then delete[] the previous array.

Just use std::vector - let it do all that stuff for you...




回答2:


In general C++ arrays cannot be reallocated with realloc, even if the storage was allocated with malloc. malloc doesn't give you arrays. It gives pointers to usable storage. There's a subtle difference here.

For POD types, there's little difference between usable storage and actual objects. But for non-POD types, usable storage and objects are totally different things.

realloc gives you a larger portion of usable storage. It manipulates storage not objects. That may work fine for POD types, but for other types it's a recipe for disaster.




回答3:


Use ::std::vector.

Take a look at this question or this question for more details.



来源:https://stackoverflow.com/questions/9586345/reallocating-memory-of-a-c-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!