Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to move unique_ptr array into another

Tags:

c++

c++11

stl

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?

like image 390
Victor Stone Avatar asked Jul 11 '16 22:07

Victor Stone


1 Answers

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());
like image 196
Victor Stone Avatar answered Nov 07 '22 21:11

Victor Stone