I have an array contained in a std::unique_ptr and I want to move the contents into another array of the same type. Do I need to write a loop to move the elements one by one or can I use something like std::move?
const int length = 10;
std::unique_ptr<int[]> data(new int[length]);
//Initialize 'data'
std::unique_ptr<int[]> newData(new int[length]);
//Fill 'newData' with the contents of 'data'
EDIT: Also, what if the arrays are different sizes?
Given destination array defined as:
std::unique_ptr<int[]> destPtr(new int[destLength]);
And source array defined as:
std::unique_ptr<int[]> srcPtr(new int[srcLength]);
Where its guaranteed that srcLength <= destLength
, you can use std::move as follows:
const auto &srcBegin = srcPtr.get();
std::move(srcBegin, std::next(srcBegin, srcLength), destPtr.get());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With