Can you reuse the moved std :: string?

In 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; } 

Is it possible to reuse the string curr std :? This fragment seems to work: after curr moves the result vector inside, it becomes empty. I want to be sure that this is not undefined behavior in the standard, and it does not work just because of luck.

+5
source share
3 answers

With a few exceptions (for example, smart pointers), displaced objects remain in a valid but undefined state.

In std::string , which uses small string optimization, for example, if the string is small, there is no dynamic allocation, and moving is a copy. In this case, it is absolutely fair for the implementation to leave the original row intact and not bear the additional cost of emptying the row.

+10
source

From http://en.cppreference.com/w/cpp/utility/move

... all standard library functions that accept rvalue reference value parameters (e.g. std :: vector :: push_back) ensure that the argument is moved-out in a valid but unspecified state.

+3
source

Maybe this link will be useful

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

+1
source

Source: https://habr.com/ru/post/1208648/


All Articles