Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

memory

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

like image 297
codingbash Avatar asked May 11 '15 00:05

codingbash


1 Answers

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.

like image 61
Pradhan Avatar answered Oct 16 '22 15:10

Pradhan