std :: uninitialized_copy&之间的区别std :: copy? [英] Difference between std::uninitialized_copy & std::copy?
问题描述
std::uninitialized_copy
和std::copy
有什么区别?什么时候应该使用?
What is the difference between std::uninitialized_copy
and std::copy
and when should I use which?
推荐答案
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;
因为在p
处没有类型为T
的对象可以调用赋值运算符.相反,您将使用 placement在位置p
处构造一个类型为T
的对象. new
:
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
仅在实现上述代码段的范围版本时处理要复制到未初始化存储区的范围.
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.
这篇关于std :: uninitialized_copy&之间的区别std :: copy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!