I’m using std::vector to store an image in my Image class. I’m having a bit trouble understanding how they work. A function which rotates the image:
void Image :: resize (int width, int height)
{
//the image in the object is "image"
std::vector<uint8_t> vec; //new vector to store rotated image
// rotate "image" and store in "vec"
image = vec; // copy "vec" to "image" (right?)
//vec destructs itself on going out of scope
}
Is there any way to prevent the last copy? Like in Java, just by switching references? It would be nice if any copying is prevented.
You can use
std::vector::swap:This is a essentially a pointer swap, the contents are transferred rather than copied. It is perfectly valid since you don’t care about the contents of
vecafter the swap.In C++11 you can “move” the contents of
vecintoimage:This operation has essentially the same effect, except that the state of
vecis less well defined (it in a self consistent state but you cannot make any assumptions about its contents… but you don’t care anyway because you know you are discarding it immediately).