Difference between std::uninitialized_copy & std::copy?

可紊 提交于 2020-04-05 08:04:07

问题


What is the difference between std::uninitialized_copy and std::copy and when should I use which?


回答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.



来源:https://stackoverflow.com/questions/30158192/difference-between-stduninitialized-copy-stdcopy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!