【发布时间】:2014-09-20 11:21:38
【问题描述】:
我原以为std::make_move_iterator 将始终移动内容,但似乎不是。
看起来它正在移动 vector<string> 中的元素,而不是 vector<int> 中的元素。
见下面代码sn-p:
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
void moveIntVector()
{
std::cout << __func__ << std::endl;
std::vector<int> v1;
for (unsigned i = 0; i < 10; ++i) {
v1.push_back(i);
}
std::vector<int> v2(
std::make_move_iterator(v1.begin() + 5),
std::make_move_iterator(v1.end()));
std::cout << "v1 is: ";
for (auto i : v1) {
std::cout << i << " ";
}
std::cout << std::endl;
std::cout << "v2 is: ";
for (auto i : v2) {
std::cout << i << " ";
}
std::cout << std::endl;
}
void moveStringVector()
{
std::cout << __func__ << std::endl;
std::vector<std::string> v1;
for (unsigned i = 0; i < 10; ++i) {
v1.push_back(std::to_string(i));
}
std::vector<std::string> v2(
std::make_move_iterator(v1.begin() + 5),
std::make_move_iterator(v1.end()));
std::cout << "v1 is: ";
for (auto i : v1) {
std::cout << i << " ";
}
std::cout << std::endl;
std::cout << "v2 is: ";
for (auto i : v2) {
std::cout << i << " ";
}
std::cout << std::endl;
}
int main()
{
moveIntVector();
moveStringVector();
return 0;
}
结果是:
moveIntVector
v1 is: 0 1 2 3 4 5 6 7 8 9 # I expect this should be `0 1 2 3 4` as well!
v2 is: 5 6 7 8 9
moveStringVector
v1 is: 0 1 2 3 4
v2 is: 5 6 7 8 9
我在Ubuntu 14.04, gcc 4.8.2,代码是用-std=c++11编译的
你能解释一下为什么std::make_move_iterator 在vector<int> 和vector<string> 上有不同的行为吗? (或者它是一个错误?)
【问题讨论】:
-
请注意,在您的
moveStringVector的v1输出中,移动留下的空字符串末尾有多余的空格。 -
Err...您是否认真地创建了两个函数
move*Vector(),它们以完全相同的方式处理两种类型的 template 类,并且与字母 99% 相同?谁的名字甚至表明类型是唯一的区别?这让我非常困扰,以至于我感到这种敦促现在就去并将其合并到一个模板函数中;-)。我的意思是,即使输出运算符也是一个模板(与printf不同)。唯一的区别在于可以作为数组传入的初始化。或者,实际上,使用初始化列表初始化向量。
标签: c++ string c++11 vector move-semantics