Search code examples
c++vectorstl

Is it possible to extract data from std::vector without copying it? (and make the vector forget it)


I have a std::vector<byte> object and I want to extract data from it without copying. It may contain megabytes of data. So, if I copy data I would lose performance. Is it possible to extract the data from the vector and make it forget about data, that is, that it doesn't free memory for the data after destruction? Hope for your help! Thanks in advance!

P.S: extract in this case means just get a raw pointer to the data and make vector forget about it (i.e don't free the memory after destruction)


Solution

  • No, It is not possible to extract part of data from vector as far as I know.

    It is not compatible with structure of vector that provides its data in a continuous part of memory. std::vector memory is continues, so if it was possible to move part of its memory to another place, you need to shift reminder of memory to keep it continuous. It will be a huge burden itself.

    I personally suggest to pass main vector by pointer/reference and use required parts directly as needed.

    If you need to move whole data of std::vector to another place, you can just use std::move() to do so. You can even use std::swap() to swap contents of 2 vector together.