gpt4 book ai didi

c++ - 为什么 std::move 与常量对象一起工作

转载 作者:行者123 更新时间:2023-11-27 22:39:36 26 4
gpt4 key购买 nike

为什么下面的代码是合法的。根据我的理解,测试的构造函数参数 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,因此不会调用移动构造函数。它将调用复制构造函数。

尝试一下。你会看到的。

关于c++ - 为什么 std::move 与常量对象一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com