【发布时间】:2020-08-01 00:05:52
【问题描述】:
我试图理解移动迭代器。这是来自https://en.cppreference.com/w/cpp/iterator/make_move_iterator的示例代码
#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <iterator>
int main()
{
std::vector<std::string> s{"one", "two", "three"};
std::vector<std::string> v1(s.begin(), s.end()); // copy
std::vector<std::string> v2(std::make_move_iterator(s.begin()),
std::make_move_iterator(s.end())); // move
std::cout << "v1 now holds: ";
for (auto str : v1)
std::cout << "\"" << str << "\" "; //return one, two, three
std::cout << "\nv2 now holds: ";
for (auto str : v2)
std::cout << "\"" << str << "\" "; //return one, two, three
std::cout << "\noriginal list now holds: ";
for (auto str : s)
std::cout << "\"" << str << "\" "; //return nothing
std::cout << '\n';
}
所以移动迭代器按预期移动。但是当我做了一些小改动时:
std::vector<int> s{1, 2, 3};
std::vector<int> v1(s.begin(), s.end()); // copy
std::vector<int> v2(std::make_move_iterator(s.begin()),
std::make_move_iterator(s.end())); // move
s 仍然引用 {1, 2, 3} 尽管移动。这是有原因的吗?
【问题讨论】:
-
移动
ints 没有多大意义,因此移动与复制几乎相同。我也不建议在移动对象后尝试使用它们。您从移动对象获得的唯一保证是您可以安全地销毁它。绝对不保证它包含的内容。