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
6 Answers
+ 5
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
+ 2
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
+ 1
Bob_Li , I don't want to combine c and c++. It's like I am looking for equivalent of realloc in c++. Vector is on higher level and looking for something on lower level
4th Feb 2025, 11:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
That sounds good Shardis Wolfe . I thought we have something directly available to us rather than we doing new[] , copy and delete[]
4th Feb 2025, 11:06 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta if you use the Vector container class, you have the resize() method readily available.
5th Feb 2025, 12:24 AM
Shardis Wolfe
0
https://stackoverflow.com/questions/68210877/why-is-there-no-realloc-equivalent-to-the-new-delete-family what you're describing feels like reallocating arrays. the standard answer for that is: if you're using c++, just use vectors and save yourself the trouble.
5th Feb 2025, 1:17 AM
Bob_Li
Bob_Li - avatar