gpt4 book ai didi

c++ - 方法冗余 move 调用的 move 语义

转载 作者:行者123 更新时间:2023-11-30 00:43:58 24 4
gpt4 key购买 nike

说我有这门课

struct Test {
std::string a;
void setA(std::string&& input) {
a = input;
input = "";
}
}

在这里,我将 input 的内容 move 到 a 中,然后将 input 置于安全的可破坏状态。这是 move 语义的经典用法,我可以在其中避免复制。

现在说我有这门课

struct Test {
std::string a;
void setA(std::string&& input) {
DoSomeWork(input);
}
void DoSomeWork(std::string&& other) { /* ... */}
}

这仍然是正确的吗?或者我应该使用 DoSomeWork(std::move(input));?我不知道在这种情况下是否需要 move 。


注意。在案例 1 中,我收到一个右值引用作为输入,我使用经典方法。

void setA(std::string&& input) {
a = input; //input is an rvalue referece and I "transfer" its content into a
input = ""; //maybe useless but in some books (including c++ primer) I've seen that it's good practice to "reset" the moved-from object and leave it in a destructable state!

我明白了。我无法理解的是:

void setA(std::string&& input) {
//recall that DoSomeWork accepts a std::string&&
DoSomeWork(input);
}

在这里,如果我想将 input 传递给函数并 move 它,我不知道是否需要 std::move。我已经有一个右值引用,所以 move 过程是自动的吗?还是需要 std::move 调用?

最佳答案

Here I move the content of input into a

没有。您正在将 input 的内容复制到 a

您可能会混淆类型和 value categories .作为命名参数,input 是一个左值;给定 a = input;,将调用复制赋值运算符,但不会调用 move 赋值运算符。

and then I leave input on a safe destructable state.

多余的,应该交给std::string的 move 赋值运算符来完成。

是的,你应该使用 std::moveinput 转换为右值,例如

void setA(std::string&& input) {
a = std::move(input); // input is move assigned to a, and left with undetermined but valid state
}

void setA(std::string&& input) {
DoSomeWork(std::move(input));
}

关于c++ - 方法冗余 move 调用的 move 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51445198/

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