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

穿精又带淫゛_ 提交于 2019-12-12 10:37:23

问题


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.


回答1:


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.




回答2:


May be, this link will be useful

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




回答3:


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

...all standard library functions that accept rvalue reference parameters (such as std::vector::push_back) are guaranteed to leave the moved-from argument in valid but unspecified state.



来源:https://stackoverflow.com/questions/27376623/can-you-reuse-a-moved-stdstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!