为什么 std::move 适用于常量对象

why std::move works with constant object

本文关键字:常量 对象 适用于 move std 为什么      更新时间:2023-10-16

为什么下面的代码是合法的。根据我的理解,测试的构造函数参数 s1 指的是常量对象,在调用 std::move(( 之后,对象的状态应该改变,所以它应该给出错误但它的工作。

#include <iostream>
#include<memory>
#include <string>
using namespace std;
class test
{
string s;
public:
test( const string& s1) : s(std::move(s1))
{
}
};
int main()
{
test t1("data");
}

因为std::move使移动对象成为可能。它实际上不会移动任何东西。那将是s的移动构造函数。

但是由于此处移动的结果仍然是const因此它不会调用移动构造函数。它将调用复制构造函数。

试试吧。你会知道的。