gpt4 book ai didi

c++ - 在右值引用参数上使用 std::move 的原因

转载 作者:行者123 更新时间:2023-12-01 19:48:00 24 4
gpt4 key购买 nike

我正在读一本关于用C++实现的数据结构的书,我不明白代码片段,它是 vector 类的一部分

void push_back(object &&x) {
//do something
objects[size++] = std::move(x);
}

我知道 std::move 返回对象的右值引用,但是 push_back 成员函数已经具有右值引用 x 作为参数,这里的std::move是不是不需要了?

另一个问题是,如果我们有一个类对象的右值引用,如果我们想调用 move 而不是 copy right,我们仍然需要在其成员上使用 std::move 吗?就像下面的代码:

A& operator=(A&& other) {
member = std::move(other.member);
return *this;
}

最佳答案

isn't the std::move here unnecessary?

没有。类型和 value categories是不同的东西。

(强调我的)

Each C++ expression (an operator with its operands, a literal, a variable name, etc.) is characterized by two independent properties: a type and a value category.

The following expressions are lvalue expressions:

the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as std::cin or std::endl. Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

std::move 将左值转换为右值(x值)。作为命名变量,x 是一个左值,std::move 将其转换为 objects[size++] = std::move(x);< 中的右值 那么应该使用 move 赋值运算符。否则,将使用复制赋值运算符;左值不能绑定(bind)到右值引用。

we still need to use std::move on its member if we want to call move instead of copy right?

是的,原因与上面相同。

关于c++ - 在右值引用参数上使用 std::move 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761148/

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