你可以重用一个移动的std :: string? [英] Can you reuse a moved std::string?

查看:231
本文介绍了你可以重用一个移动的std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定此示例:

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

我可以重复使用 curr std:string?这个代码片段似乎工作: curr 被移动到
结果向量中,它变为空。

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.

推荐答案

我想确定这不是标准中未定义的行为,除了少数例外(例如智能指针),移动对象保留在有效但未指定的状态。

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

std: :string ,它使用小字符串优化,例如,如果字符串小,没有动态分配,移动是一个副本。在这种情况下,完全有效的实现离开源字符串不变,而不会产生额外的成本清空字符串。

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.

这篇关于你可以重用一个移动的std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆