In C we used malloc(), free()
, but in C++ youare using new, delete
, but in C we also have realloc
, which will alloc the new block and copy the old data (common minimum) and then free the old data bock. So what is the C++ version of that? I can write my own of course, but is there a builtin thing?
main() {
int i; char *x = malloc(3);
x[0] = 10;
x[1] = 20;
x[2] = 30;
realloc(x, 4);
x[3] = 40;
for (i = 0; i < 4; i++) printf("%i\n", x[i]);
}
realloc
isn't used in C++ because C++ wants to use its copy and default constructors and destructors for things like this in general. But if you got plain old types that you want to handle as fast as possible, there is no reason not to roll your own array class that does what you want. I'm surprised there isn't one that's mostly STL-compatible already in the top Google page.There's no
new
/delete
equivalent ofrealloc
in C++.From Bjarne Stroustrup's FAQ :
If you want a resizeable container, just use
std::vector
, otherwise stay withmalloc
,realloc
andfree
.And, to answer your last question, the C++ version of your code would be :
C++ doesn't have a
new/delete
equivalent of C'srealloc
.The probable reason (although it is not mentioned anywhere in the Standard) is because of constructors that can throw: how should it behave if, while reallocating, a constructor throws? The handling of this case is best left to the programmer because there is not one true answer.
Let's see what Bjarne Stroustrup thinks!
Why doesn't C++ have an equivalent to realloc()?