Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move a std::vector into a raw array in C++

How can I move the contents of std::vector into an array safely without copying or iterating over all elements?

void someFunc(float* arr, std::size_t& size)
{
   std::vector<float> vec(5, 1.5f);
   // do something with the data

   size = vec.size();
   arr = vec.data(); // this doesn't work, as at the end of the function the data in std::vector will be deallocated

}

main()
{
   float* arr;
   std::size_t size{0};

   someFunc(arr, size);

   // do something with the data
   delete [] arr;
}

How can I assign my array with the data in std::vector and making sure that deallocation will not be called on std::vector? Or maybe any other ideas to go around this?

like image 904
Bobo Feugo Avatar asked Oct 02 '19 15:10

Bobo Feugo


People also ask

How do I copy a vector element to an array?

The elements of a vector are contiguous. Otherwise, you just have to copy each element: double arr[100]; std::copy(v. begin(), v.

Can you pass a vector as an array?

Yes. Assuming v. size() > 0 , this is safe (If the vector is empty, then v[0] results in undefined behavior). The elements of a std::vector container are stored contiguously, just like in an ordinary array.

Is std :: array movable?

std::array is movable only if its contained objects are movable. std::array is quite different from the other containers because the container object contains the storage, not just pointers into the heap. Moving a std::vector only copies some pointers, and the contained objects are none the wiser.


1 Answers

You can't.

A vector owns its buffer. You cannot steal it.

You will have to copy/move the elements individually, optionally using a helper algorithm that does the iteration for you (std::copy/std::move).

(Also note that, since your element type is just float, a move here is a copy.)

(Also note that this std::move, the algorithm, is not the same as std::move, the rvalue cast.)


Consider whether you really need to do this. You can treat the vector's data as an array using vec.data() whenever you need to, as long as you keep the vector alive. Surely that's better than sacrificing RAII?

like image 137
Lightness Races in Orbit Avatar answered Oct 11 '22 12:10

Lightness Races in Orbit