I was expecting that std::make_move_iterator
will always move contents, but it seems not.
It looks like it is moving elements in vector<string>
but not in vector<int>
.
See the below code snippet:
#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;
}
The result is:
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
I'm on Ubuntu 14.04, gcc 4.8.2
and the code is compiled with -std=c++11
Could you explain why std::make_move_iterator
have different behaviour on vector<int>
and vector<string>
? (Or is it a bug?)
moveStringVector
's output forv1
, there are extra spaces at the end from the empty strings left over from the move. – Tigermove*Vector()
which handle a template class for two types in exactly identical fashion and are 99% identical to the letter? Whose name even indicates that the type is the only difference? It's bothering me so much that I feel this urge to go right now and consolidate that into a template function ;-). I mean, even the output operator is a template (as opposed toprintf
). The only difference would be in the initialization which could be passed in as an array. Or, actually, initialize the vector with an initializer list. – Saltus