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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…