What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?

There’s no new/delete equivalent of realloc in C++.

From Bjarne Stroustrup’s FAQ :

Why doesn’t C++ have an equivalent to realloc()?

If you want to, you can of course use 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. In C++, a better way of
dealing with reallocation is to use a standard library container, such
as vector, and let it grow naturally
.

If you want a resizeable container, just use std::vector, otherwise stay with malloc, realloc and free.

And, to answer your last question, the closest C++ version of your code would be:

main() {
    std::vector<char> x(3);
    x[0] = 10;
    x[1] = 20;
    x[2] = 30;
    x.resize(4);
    x[3] = 40;
    for (int i = 0; i < 4; i++) std::cout << x[i] << std::endl;
}

But that is not the standard way of using a vector and provide little benefits versus simply:

main() {
    std::vector<char> x;
    x.push_back(10);
    x.push_back(20);
    x.push_back(30);
    x.push_back(40);
    for (int i = 0; i < 4; i++) std::cout << x[i] << std::endl;
}

Leave a Comment