Lets say I have a function to get data into an std vector:
void getData(std::vector<int> &toBeFilled) {
// Push data into "toBeFilled"
}
Now I want to send this data to another function, that should free the data when finished:
void useData(int* data)
{
// Do something with the data...
delete[] data;
}
Both functions (getData and useData) are fixed and cannot be changed. This works fine when copying the data once:
{
std::vector<int> data;
getData(data);
int *heapData = new int[data.size()];
memcpy(heapData, data.data(), data.size()*sizeof(int));
useData(heapData);
data.clear();
}
However, this memcpy operation is expensive and not really required, since the data is already on the heap. Is it possible to directly extract and use the data allocated by the std vector? Something like (pseudocode):
{
std::vector<int> data;
getData(data);
useData(data.data());
data.clearNoDelete();
}
Edit:
The example maybe doesn't make too much sense, since it is possible to just free the vector after the function call to useData. However, in the real code, useData is not a function but a class that receives the data, and this class lives longer than the vector...