#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;
}
}
運(yùn)行結(jié)果
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
說(shuō)明
1、使用std::move操作vector元素時(shí)驼鹅,原vector元素將不再可用榨馁,但原vector可以正常遍歷。因?yàn)閟td::move操作的是元素中的具體成員酝陈,而非元素整體床玻,所以新vector元素的地址與原vector元素是不同的
2、std::move只會(huì)操作class類(lèi)型的成員沉帮,而不會(huì)操作基本類(lèi)型锈死,示例中age成員仍得到保留
3贫堰、如果將“//xxx”行加個(gè)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
說(shuō)明,std::move對(duì)vector元素的操作無(wú)效待牵,仍然調(diào)用了內(nèi)存拷貝