If memory is allocated with malloc
(as opposed to new
) and an object is moved into that memory, is that valid C++?
Let's say I allocate memory for an array of n objects of type T
, and I have a range of n objects of type T
that I want to move into that, is this valid:
T* next = (T *)malloc(n*sizeof(T));
T* t = std::begin(my_range);
while (we still have more Ts) {
*next = std::move(*t);
++next;
++t;
}
This seems to work, but I'm curious as to why it would since we never new the objects in the allocated memory that we move to.
My guess is placement new is the correct way to do it:
while (we still have more Ts) {
new (next) T(*t);
++next;
++t;
}
but I'd like to know WHY the first one is incorrect, and if so, if it just works by luck or because T
happens to be a POD.