开发者

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

开发者 https://www.devze.com 2023-01-06 04:39 出处:网络
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:

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


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.


No.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消