简体   繁体   中英

C++11 - Move each element of an array (raw array, std::array, std::vector) individually?

In C++11 with all it's move semantics and such, one may wonder what can actually be moved. An example of this are arrays. Is it possible to move each element of raw arrays,

int array1[8];
int array2[8];
array1[0] = std::move(array2[0]);

std::arrays,

std::array<int, 8> array1;
std::array<int, 8> array2;
array1[0] = std::move(array2[0]);

and std::vectors

std::vector<int> array1;
std::vector<int> array2;
array1[0] = std::move(array2[0]);

individually?

Of course, assuming that array1 and array2 is properly initialized with some data in your examples. When you're dealing with individual array elements in the manner you describe, it's exactly the same process as when moving single variables.

Foo var1;
Foo var2;
var1 = std::move(var2);

Here's a live example of your three code snippets in action. .

Obviously, what's "left over" in the source variable after moving depends on the variable's type, but as long as you don't need to read anything from the source variable, then you're fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM