gpt4 book ai didi

c++ - 如果我将本地对象 move 到函数中,之后它仍然有效吗?

转载 作者:IT老高 更新时间:2023-10-28 22:16:39 25 4
gpt4 key购买 nike

所以,这提供了预期的输出:

void f(std::string&& s)
{
s += " plus extra";
}

int main(void)
{
std::string str = "A string";
f( std::move(str) );
std::cout << str << std::endl;

return 0;
}

A string plus extra

也就是说,当我在 Ideone 上运行它时它可以工作,但它是 UB 吗?在调用 f 之前和之后添加额外的字符串初始化并没有改变任何东西。

最佳答案

它是有效的,而不是 UB。

这也是可怕的混淆代码。 std::move(s) 只不过是对右值的强制转换。它本身实际上根本不会生成任何代码。它的唯一目的是将左值转换为右值,以便客户端代码可以重载左值/右值表达式(在这种情况下为 string)。

对于这种情况,您应该通过左值引用:

void f(std::string& s)
{
s += " plus extra";
}
...
f( str );

或者,按值传递并返回一个新字符串:

std::string f(std::string s)
{
s += " plus extra";
return s;
}
...
str = f( std::move(str) );

关于c++ - 如果我将本地对象 move 到函数中,之后它仍然有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226100/

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