My question specifically is in regards to arrays, not objects.
There a few questions on SO about malloc()
/free()
versus new
/delete
, but all of them focus on the differences in how they are used. I understand how they are used, but I don't understand what underlying differences cause the differences in usage.
I often hear C programmers say that malloc()
and 'free() are costly operations, but I've never heard a C++ programmer say this about
new and
delete. I've also noticed that C++ doesn't have an operation that corresponds to C's
realloc()`.
If I were writing an equivalent to C++'s vector
class, I would want to avoid copying the entire array when resizing it, but with new
and delete
you have to copy. In C, I would simply realloc()
. It's worth noting that realloc()
might just copy the entire array, but my impression was that it used the same pointer and allocated less space for it, at least when sizing down.
So my question is, how do the algorithms used by malloc()
and free()
differ from those used by new
and delete
. More specifically, why does the C way have a stigma of being more expensive, and why doesn't the C++ way allow resizing without copying?