views:

78

answers:

4

Hi,

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....

Thanks

+11  A: 

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.

Thomas
+1 for recommending std::vector. Can't do that enough it seems :)
rubenvb
+3  A: 

No.

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

array[5] = MyType();   // note no  `new` here.
James Curran
+1: Thanks. This was what I thought.
Martijn Courteaux
A: 

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

sharptooth
Yes, you can. It's an advanced technique, though, and given that the question is pretty basic, it's probably not what he should be doing.
Thomas
@Thomas: Yes, but this solution will not require an assignment operator which is good.
sharptooth
@Thomas: Haha! Yes indeed. The question is pretty basic... But I was mixing up `new T[...]` and a simple `new`
Martijn Courteaux
+2  A: 

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();
Justin Ardini