#include <vector>
#include <string>
#include <iostream>
class student {
public:
std::string name;
int age;
student(const std::string & _name, const int & _age): name(_name), age(_age){}
};
int main()
{
std::vector<student> student_vec;
student_vec.emplace_back(student("mary", 15));
student_vec.emplace_back(student("mike", 17));
student_vec.emplace_back(student("tom", 16));
std::vector<student> student_vec_move;
std::cout << "student_vec" << std::endl;
for (auto & s : student_vec) //xxx
{
std::cout << s.name << " " << s.age << "\t" << &s << std::endl;
student_vec_move.emplace_back(std::move(s));
}
std::cout << "student_vec: after std::move" << std::endl;
for (const auto & s : student_vec)
{
std::cout << s.name << " " << s.age << "\t" << &s << std::endl;
}
std::cout << "student_vec_move" << std::endl;
for (auto & s : student_vec_move)
{
std::cout << s.name << " " << s.age << "\t" << &s << std::endl;
s.name = s.name + "++";
}
std::cout << "student_vec_move: after modify" << std::endl;
for (auto & s : student_vec_move)
{
std::cout << s.name << " " << s.age << "\t" << &s << std::endl;
}
std::cout << "student_vec: after modify" << std::endl;
for (const auto & s : student_vec)
{
std::cout << s.name << " " << s.age << "\t" << &s << std::endl;
}
}
运行结果
student_vec
mary 15 0x25a70f0
mike 17 0x25a7100
tom 16 0x25a7110
student_vec: after std::move
15 0x25a70f0
17 0x25a7100
16 0x25a7110
student_vec_move
mary 15 0x25a7140
mike 17 0x25a7150
tom 16 0x25a7160
student_vec_move: after modify
mary++ 15 0x25a7140
mike++ 17 0x25a7150
tom++ 16 0x25a7160
student_vec: after modify
15 0x25a70f0
17 0x25a7100
16 0x25a7110
说明
1、使用std::move操作vector元素时,原vector元素将不再可用,但原vector可以正常遍历。因为std::move操作的是元素中的具体成员,而非元素整体,所以新vector元素的地址与原vector元素是不同的
2、std::move只会操作class类型的成员,而不会操作基本类型,示例中age成员仍得到保留
3、如果将“//xxx”行加个const改为
for (const auto & s : student_vec) //xxx
则输出为
student_vec
mary 15 0x217b0f0
mike 17 0x217b100
tom 16 0x217b110
student_vec: after std::move
mary 15 0x217b0f0
mike 17 0x217b100
tom 16 0x217b110
student_vec_move
mary 15 0x217b140
mike 17 0x217b150
tom 16 0x217b160
student_vec_move: after modify
mary++ 15 0x217b140
mike++ 17 0x217b150
tom++ 16 0x217b160
student_vec: after modify
mary 15 0x217b0f0
mike 17 0x217b100
tom 16 0x217b110
说明,std::move对vector元素的操作无效,仍然调用了内存拷贝