简体   繁体   中英

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?

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?

This would have been handy for me for stealing a "typed" vector contents into an "untyped" vector.

This is what I want to do:

std::vector<uint8_t>­one;
std::vector<V> other = std::move(one);

When I know that the contents are exactly what I expect (there is a runtime type info field)

I would use this to do 'move semantics' between an untyped and a typed class where part of the underlying representation is in a vector - just in the typed case it is vector of Vs.

Think of it as a different "view" of the data. In general cases the data is untyped as there are special edge-cases, but after handling them via branching it would be handy to handle the "normal" cases type safe ways..

I see I can implement this behaviour if I throw out std::vector and do my implementation using direct pointer arithmetic as then I can access that in move construction, but I would love to not give up on vectors...

Just wanted to add this to show what kind of rationale might be behind these kind of questions and I think sometimes it is valid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM