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?