2

std::vector用来在我的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
}

有什么办法可以防止最后一个副本?就像在 Java 中一样,只是通过切换引用?如果防止任何复制,那就太好了。

4

1 回答 1

10

您可以使用std::vector::swap

image.swap(vec);

这本质上是一个指针交换,内容是转移而不是复制。这是完全有效的,因为您不关心vec交换后的内容。

在 C++11 中,您可以将以下内容“移动”vecimage

image = std::move(vec);

此操作具有基本相同的效果,只是状态vec不太明确(它处于自洽状态,但您不能对其内容做出任何假设......但无论如何您都不在乎,因为您知道您正在丢弃它立即地)。

于 2013-02-13T12:52:28.517 回答