Search code examples
c++stlvectorrealloc

Is STL vector a better version of realloc?


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++?

Solution

  • 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.