0

Counter part of realloc

Hi We have option of adding more allocation to existing resource by using realloc in c. What is the way for C++? I have a ptr to my class for three objects and need to re allocate this to 5 objects.

3rd Feb 2025, 8:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 4
if you need to do reallocation, use vector instead. mixing C with C++ is not recommended, from most discussions I've read.
3rd Feb 2025, 9:05 AM
Bob_Li
Bob_Li - avatar
+ 1
Ketan Lalcheta For simple cases, you can use new[] to create larger space, copy from old to new, and delete[] the old space. For more complex situations, you can use the Vector container library and call its resize() method as needed which essentially automates the whole new[], copy, delete[] process. All the various alloc functions from C worked with raw memory. You had to figure out how much memory one instance of your class needed and multiply that by how many objects needed to store. Also the alloc functions do not deal well with exceptions which often led to memory leaks.
3rd Feb 2025, 11:51 PM
Shardis Wolfe