Reputation: 68847
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
Upvotes: 2
Views: 6031
Reputation: 181725
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.
Upvotes: 11
Reputation: 9866
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();
Upvotes: 2
Reputation: 103485
No.
The individual elements of the array were not new'd, just the array itself was.
array[5] = MyType(); // note no `new` here.
Upvotes: 3