Is STL vector a better version of realloc?

aJ. picture aJ. · Apr 15, 2009 · Viewed 7.1k times · Source

In C++, I believe, a better way of dealing with reallocation is to use a STL vectors, as it guarantees the contiguous storage locations.

I have couple question to understand the difference:

  1. Is there any scenario in which I need to prefer realloc over vector ?
  2. Is there anything else ( apart from vector ) which is equivalent to realloc in C++?

Thanks,

Answer

dirkgently picture dirkgently · Apr 15, 2009

It is only vector, which is guaranteed to have contiguous memory. Not the others.

realloc is a C memory management function. It's use is not encouraged in C++ code. Here's Stroustrup telling you why: Why doesn't C++ have an equivalent to realloc()?

However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occasionally does copy its argument array.