Proper way to move unique_ptr array into another

时间:2016-07-11 22:31:09

标签: 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?

3 个答案:

答案 0 :(得分:4)

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());

答案 1 :(得分:1)

Initialization using std::move. The data's content will be discarded:

 std::unique_ptr<int[]> newData = std::move(data);

what if array of different size?

I presume it is something like:

 const int length = 10;
 std::unique_ptr<int[]> data(new int[length]);
 //Initialize 'data'

 ...

 const int length2 = 20;
 std::unique_ptr<int[]> newData(new int[length2]);
 std::copy_n(data.get(), std::min(length, length2), newData.get());

If newData has a fixed size consider using std::array<int, SIZE> in place of int[] to avoid type decay.

答案 2 :(得分:1)

You can use swap:

#include<memory>
#include<cassert>

int main() {
    std::unique_ptr<int[]> a{new int[42]};
    std::unique_ptr<int[]> b{};
    a[0] = 42;
    a.swap(b);
    assert(b[0] == 42);
}

Also, what if the arrays are different sizes?

You can use swap.


Consider that length isn't an information that comes along with the unique pointer.
Because of that, you still have to swap the lengths of the two arrays somehow.

Moreover, if you want to move data, but also you want to maintain room for extra data in the second array, a possible approach would be the classical for loop with a std::move to actually move the data from a to b.
More expensive (linear complexity, fair enough).