lundi 25 juillet 2016

Returning rvalue reference to std::vector

This question already has an answer here:

I'm not exactly clear on the question I'm asking, but it boils down to, why does the following code crash?

#include <string>
#include <vector>
#include <iostream>

using namespace std;

static std::vector<std::string>&& tokenize(const std::string& input) {
  std::vector<std::string> tokens;
  auto start_index = input.begin();
  if(*start_index == '/')
    ++start_index;

  for(auto index = start_index; index != input.end(); ++index) {
    if(*index == '/') {
        std::string token(start_index, index);
        tokens.push_back(token);
        start_index = index + 1;
    }
    else if(index+1 == input.end()) {
        std::string token(start_index, index+1);
        tokens.push_back(token);
    }
  }

  return std::move(tokens);
}

int main() {
    auto tokens = tokenize("/a/b/c");
    for(auto& token : tokens )
        cout << token << endl;
}

On Linux, under GCC 5.4.0, it segfaults in the destructors at the end of the main function. Does std::move() not work correctly on a std::vector<std::string>?

Aucun commentaire:

Enregistrer un commentaire