As others point out void
has no defined size so void*
can't be indexed as an array.
Where does temp[1]
begin?
A naïve fix of:
T *temp = std::malloc((end-begin) * sizeof(T));
Is just as bad when used in conjunction with:
temp[i] = std::move(array[i]);
That code will call the assignment operator and if non-trivial will fail when acting on the garbage that is in temp[i]
. For example, if the assignment explicitly or implicitly de-allocates resources in the assignment target it will operate on the uninitialized temp[i]
and fail.
If (IF!) you did this the correct code would be:
std::memcpy(temp+i*sizeof(i),array[I],sizeof(T));
That line of code is essentially assuming that T
is a trivially-copyable type.
The first line is assuming objects of T
have a trivial default constructor.
If T
has a trivial default constructor most compilers will optimize the element initialization away (which is what I assume the asker is trying to avoid).
So the recommended code (using a for
loop) is:
T* temp= new T[end-being];
for(unsigned int i=begin;i<end;++i){
temp[i-begin]=array[i];
}
NB: This code also fixes a bug in the original code that breaks when begin!=0
.
The code appears to be copying a sub-section from the middle of array
to the start of temp
but forgets to start at index 0
of temp
.
But the recommended C++ approach to such copying is:
T* temp= new T[end-being];
std::copy(array+begin,array+end,temp);
Good implementations will determine and take advantage of any bulk memory operations where possible.
So implicitly this should result in std::memmove(temp,array,(end-begin)*sizeof(T));
if valid.
The only final twist that a compiler might not recognize is that the potentially slightly more efficient
std::memcpy(temp,array,(end-begin)*sizeof(T));
Is actually valid in this case because we know temp
cannot overlap with array
(let alone the range being copied).
Footnote: As pointed out in the comments the most conventional C++ approach is to use std::vector
which can normally be assumed to be using these optimizations behind the scenes. However if for some reason re-architecting the application is not possible or desirable this answer provides the valid efficient way of re-writing the code provided.