Tutorial :C++: Overwrite an element in a new-created array


If I have an array created like this:

MyType *array = new MyType[10];  

And I want to overwrite one of the elements, do I have to delete first the old element like this:

delete &array[5];  array[5] = *(new MyType());  

Or is this completely wrong and do I have to work with something like "pointers to pointers" to fix this job? If so, how please....



It's an array of values, not of pointers. So you'd just do

array[5] = MyType();  

This requires MyType to support the assignment operator.

Incidentally, there's rarely a need for manual array allocation like this in C++. Do away with the new and delete and use std::vector instead:

std::vector<MyType> array(10);  array[5] = MyType();  

Note, there's no need to delete anything.



The individual elements of the array were not new'd, just the array itself was.

array[5] = MyType();   // note no  `new` here.  


You are declaring an array of MyTypes, not pointers to MyTypes. Because you don't new the elements in the array, you also don't delete them. Instead, just do:

array[5] = MyType();  

Note that you can also use std::vector<MyType> to put your MyTypes on the heap without worrying about the nuisances of C++ arrays.

std::vector<MyType> myTypes(10);  myTypes[5] = MyType();  


You can call a destructor in-place, then use placement new.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »