c++vectorstlfolly

Why does the vector returned by my C++ function contain garbage values in the caller?


I've created a simple C++ program to read and tokenize input from cin. However, while the tokens in my helper function are correct, the tokens in the caller function (main) are garbage values.

As an example, if I enter "a b c" as the input, the vector of tokens in my helper function (get_input_tokens) contains "a", "b", "c", but the vector of tokens in main contains "?", "?", "".

My understanding is that the vector should be returned by value to the caller, so a new copy of the vector should be created in the caller (main) that is identical to the original vector. Would anyone be able to give me some ideas about why this is happening?

#include <folly/String.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<folly::StringPiece> get_input_tokens() {
    string input;
    getline(cin, input);   // Enter in "a b c"
    
    vector<folly::StringPiece> tokensVec;
    folly::split(" ", input, tokensVec);

    // Print tokensVec - prints out "a", "b", "c"
    for (int i=0; i<tokensVec.size(); i++) {
        cout << tokensVec[i] << endl;
    }

    return tokensVec;
}

int main(int argc, char *argv[]) {
    auto tokensVec = get_input_tokens();

    // Print tokensVec - prints out "?", "?", ""
    for (int i=0; i<tokensVec.size(); i++) {
        cout << tokensVec[i] << endl;
    }
    return 0;
}

Reference for folly::split: https://github.com/facebook/folly/blob/master/folly/String.h#L403.


Solution

  • It's because a StringPiece holds pointers into the string it is a piece of.
    In your case, that's input, which is destroyed when the function returns and makes all the StringPieces invalid.

    You need a different type for the tokens.
    I'm not familiar with folly, but if the creators haven't lost the plot completely, std::string should work.