Reusing dyn. allocated array

Hello,

I've got a dyn. allocated array like this:
1
2
int size = 10;
MyClass* array = new MyClass[size];


Now I want to delete element at index 5 and store a different element in it's place.
Can I just call
1
2
delete array[5];
array[5] = new MyClass();

?
Does new memory get allocated or do I "recycle" memory that way?
Thanks!
You can't delete 1 element from an array like that.
1
2
3
4
5
6
7
delete [] array;//free's memory for the entire array

//reallocate dynamic memory 

//size of array should decrease because you wan't to remove an element

//create a new array with all the values except for the one you want to delete. 



Look into how to implement a copy constructor, destructor, and overloaded assignment operator. This will give you a better understanding of memory management.
Last edited on
I don't want to reallocate the memory but instead reuse it. I want to replace a element if you want.

The size of the array doesnt change!
I don't want to reallocate the memory but instead reuse it. I want to replace a element if you want.

The size of the array doesnt change!

Then what is the problem? Just replace the existing value.

1
2
array[i] = MyClass(); // recycle once...
array[i] = MyClass(); // recycle twice... and so on 

I wasn't sure this wouldn't leak memory. Thanks for confirming it!
I wasn't sure this wouldn't leak memory.

To my knowledge, in C++ you leak memory when you new it but don't delete it.

So if you eventually delete[] array; no memory leak should occur.
Topic archived. No new replies allowed.