Click here to Skip to main content
15,400,433 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an array allocated like so

C++
ClassName *var = new ClassName [NumItems];


I delete it using

C++
delete [] var;


Currently when a single item is removed I call memmove to shift everything over, but that causes delete to throw an exception when debugging. (Been shipping it this way for a decade, customers rarely use it)
C++
memmove(&var[index], &var[index + 1], sizeof(ClassName) * (NumItems - (Index + 1));


How do you properly remove an item in the middle of an array allocated this way?

I do not want to change it to an array class because I would have to change 100+ functions and do not want to spend that much time. I am just curious as to how to do it this way correctly.

What I have tried:

memmove as specified in the above explanation
Posted
Updated 2-Jul-22 10:49am
v2

The C++ library is your friend here:

C++
Class* arrayOfClass = new arrayOfClass[N];

// fill array code skipped

// delete element n of the array, leaving element N-1 in a destructible state
std::move(arrayOfClass + n, arrayOfClass + (n + 1), arrayOfClass + N);

// the only things that you may do with element N-1 are:
//   assign a new value to it
//   destruct it (e.g. when the entire array is destructed)
   
Given your code above it should look like this:


C++
size_t bytes_to_move = NumItems - index + 1;
memmove(var + index, var + index + NumItems, bytes_to_move* sizeof(ClassName));
   
v3
Quote:
Currently when a single item is removed I call memmove to shift everything over,..

Why use an array when you want to delete elements in it?
Wouldn't a vector be a better idea?
   
Comments
CPallini 1-Jul-22 16:06pm
   
Possibly because "I do not want to change it to an array class because I would have to change 100+ functions and do not want to spend that much time. I am just curious as to how to do it this way correctly"?
:-D
merano99 1-Jul-22 20:28pm
   
Yes, possibly. I don't know why anyone would have to change more than 100 functions either:-D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900