The correct way to move the unique_ptr array to another

I have an array contained in std :: unique_ptr and I want to move the contents to another array of the same type. Do I need to write a loop to move elements one at a time 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 arrays are of different sizes?

+4
source share
3 answers

This destination array is defined as:

std::unique_ptr<int[]> destPtr(new int[destLength]);

And the source array is defined as:

std::unique_ptr<int[]> srcPtr(new int[srcLength]);

Where it is 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());
+3
source

Initialization using std::move. Data content will be discarded:

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

what if the array is of different size?

, - :

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

newData , std::array<int, SIZE> int[], .

+1

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

, , ?

swap.


, length , . - length .

, , , for std::move a b.
( , ).

+1

All Articles