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?
.data()
? – Hardboiledvector<T>
on legacy functions that take aT*
. As stated, just use thedata()
member. There is no need to shuffle between vector and a regular array, if this is what you were intending to do. – Rhigolenedata()
to the top-level "old code" function, and the rest is all an array, the old code has no idea the data was being managed by a vector. Have you ever useddata()
? – Rhigolenedata()
will return a pointer to const data, but I need to modify the data – Chestyconst vector
. From a mutable vector you get a pointer-to-mutable – Herwindelete[]
on the pointer (which is a bad design to being with). – Rhigolenefree()
, ordelete
, orlib_MyBadOlLib_Free()
– Herwinstd::string::c_str()
, where the return value isconst
. Not so for a non-const vector. – Rhigolene