C++: What is the proper way of resizing a dynamically allocated array?

别来无恙 提交于 2019-12-30 04:56:15

问题


In C, I would have done it using realloc.

In C++, one would normally consider using the STL vector class.

But how do I properly resize an array in C++ without using any of the above solutions?


回答1:


There is no good equivalent of realloc in C++. You'll need to manually duplicate the array and copy the old elements over. Fortunately, thanks to the std::copy function in <algorithm>, this isn't too bad:

size_t k =  /* ... */
T* buffer = /* .. get old buffer of size k. .. */

T* newBuffer = new T[newSize];  // Assume newSize >= k
std::copy(buffer, buffer + k, newBuffer);

delete [] buffer;
buffer = newBuffer;

Hope this helps!

EDIT: Reordered the last two lines! Whoops!




回答2:


By doing what vector and realloc do internaly: make a new, bigger array, copy the content of the old one, and destroy the old one.




回答3:


int* arr = new int[20];
...
//wanna resize to 25?
int* temp = new int[25];
std::copy(arr, arr+20, temp);
delete [] arr;
arr = temp;
... //now arr has 25 elements

But, of course, you shouldn't do this :)




回答4:


If you insist on doing this yourself in C++, you probably want to do roughly like std::vector does, and allocate raw memory using the global new operator, then use placement new to create objects "in place".

Otherwise, you end up constructing objects in all the memory you allocate, and then assigning over them when you use them. Unless you know that the initial (default) object construction is lightweight, you'd rather avoid it if possible.



来源:https://stackoverflow.com/questions/5371162/c-what-is-the-proper-way-of-resizing-a-dynamically-allocated-array

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