Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you reuse a moved std::string? [duplicate]

Given this example:

 std::vector<std::string> split(const std::string& str) {
    std::vector<std::string> result;
    std::string curr;
    for (auto c : str) {
        if (c == DELIMITER) {
            result.push_back(std::move(curr)); // ATTENTION HERE!
        } else {
            curr.push_back(c);
        }
    }
    result.push_back(std::move(curr));
    return result;
}

Can I reuse the curr std:string? This snippet seems working: after curr is moved inside the result vector, it becomes empty. I want to be sure this is not an undefined behavior in the standard and it isn't working only because of luck.

like image 952
Alessandro Pezzato Avatar asked Dec 09 '14 10:12

Alessandro Pezzato


2 Answers

With a few exceptions (smart pointers, for instance), moved-from objects are left in a valid but unspecified state.

In a std::string that uses the small string optimization, for instance, if the string is small, there is no dynamic allocation, and a move is a copy. In that case it is perfectly valid for the implementation to leave the source string untouched, and not incur the extra cost of emptying the string.

like image 109
T.C. Avatar answered Oct 13 '22 17:10

T.C.


May be, this link will be useful

In short, for reuse you need to call .clear method

like image 33
RainLabs Avatar answered Oct 13 '22 18:10

RainLabs