Difference between std::uninitialized_copy & std::copy?
What is the difference between std::uninitialized_copy
and std::copy
and when should I use which?
Solution 1:
Lets say you have allocated some memory on the heap via malloc
and have a pointer T* p
to it. You end up with uninitialized storage because all malloc
does is mark a location of the size you asked for as allocated (new
on the other hand actually constructs objects and thus makes the allocated region initialized storage). Since the memory location starting from p
does not have a valid object of type T
sitting there, you cannot do this
T a;
*p = a;
since there is no object of type T
at p
to invoke the assignment operator on. Instead, you will have a construct an object of type T
at location p
using placement new
:
T a;
new (p) T{a};
std::uninitialized_copy
simply implements the range version of the above code snippet when dealing with a range that you want to copy over to uninitialized storage.