return C++ local string to another function

Viewed 338

Here is my confusion. I think s1 and s2 are function local object instance of type string, we should not return function local scope object to outside. But it seems below code works, wondering why?

vector<string> testString(){
    vector<string> result;
    string s1 = "123";
    string s2 = "456";
    result.push_back(s1);
    result.push_back(s2);

    return result;
}

void testStringWrapper(){
    vector<string> result = testString();
    for (int i=0; i<result.size(); i++) {
        cout << result[i] << endl;
    }
}
3 Answers
Related