std :: uninitialized_copy&之间的区别std :: copy? [英] Difference between std::uninitialized_copy & std::copy?

查看:99
本文介绍了std :: uninitialized_copy&之间的区别std :: copy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::uninitialized_copystd::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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆