c++ - 将 std::string 移动到函数参数

标签 c++ rvalue-reference

我想将一个大的 std::string 移动到类的成员。

这是我的代码:

#include <cassert>
#include <string>
#include <iostream>
using namespace std;

class SomeClass {
public:
    void some_method(std::string&& str) {
        my_str = str;
    }

    std::string my_str;
};

int main() {
    SomeClass some_class;

    std::string large_str(100000, 'a');

    some_class.some_method(std::move(large_str));

    assert(large_str.empty());
    assert(!some_class.my_str.empty());
    return 0;
}

移动后,我预计 large_str 为空,但此代码断言在 assert(large_str.empty()) 行失败。

我是否误解了 std::move 的语义?

最佳答案

Did i misunderstand the semantics of std::move?

部分是的。您忘记将函数参数 str 转换为右值。在 some_method 中,它又变成了左值。要解决此问题:

void some_method(std::string&& str) {
    my_str = std::move(str);
    //       ^^^^^^^^^ Necessary: invoke std::move a 2nd time
}

但请注意以下几点。 “移出”std::string 对象不是您应该断言 的对象。来自 here , 重载#8(强调我的):

Move constructor. Constructs the string with the contents of other using move semantics. other is left in valid, but unspecified state.

您不希望您的程序依赖于未指定的状态(即使碰巧某个特定实现使 std::string::size 在其资源消耗后返回 0)。

关于c++ - 将 std::string 移动到函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55280922/

相关文章:

java - C++(OpenCV) 中 k-NN 示例的问题

c++ - const T& 与 T&&

c++ - 引用与模板模板类折叠

c++ - 编译器可以自动为最后一次使用左值生成 std​​::move 吗?

c++ - 禁用 Eigen 表达式与 const 引用的临时绑定(bind)

C++无限参数到数组

c++ - 将代码从 Visual Basic 移至 C++ 问题

c++ - 有人可以解释这个 C/C++ 语法吗?

c++ - 程序纹理棋盘 OpenGL

c++ - 可以接收 T、T& 和 T&& 中的任何一个作为输入的函数,并且还可以识别其类型?