Search code examples
c++vectormoveunique-ptr

Moving an array held by a unique_ptr into a vector's array storage


Is there a way to move a unique_ptr

unique_ptr<int[]> foo;

into a vector?

vector<int> bar;

Solution

  • No, you cannot just hand vector a piece of memory and expect it to use that as its array storage. A vector's storage must come from the allocator that the vector uses.

    You could try to use allocator gimmicks to pawn the memory off to the vector in some way. But even that would be tricky, as the vector can allocate as many ints as it wants, regardless of what size you tell it.

    You can move the contents of a unique_ptr into an element of the array. Say, if you had a vector<unique_ptr<int[]>>. But you can't just slap a piece of memory into a vector.