Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c++ - Difference between std::uninitialized_copy & std::copy?

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

question from:https://stackoverflow.com/questions/30158192/difference-between-stduninitialized-copy-stdcopy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...