问题
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