gpt4 book ai didi

c++ - std::move 返回和输入引用参数

转载 作者:行者123 更新时间:2023-11-27 23:57:52 26 4
gpt4 key购买 nike

(一)

std::string doNothing(const std::string&& s)
{
return std::move(s);
}

(乙)

std::string doNothing(const std::string& s)
{
return std::move(s);
}

(测试)

const std::string str = "aaaaaa";
const auto str2 = doNothing(str);

两个问题:

  1. (A) 和 (B) 有区别吗?
  2. 在(测试)中:str 是否未定义? move 到 str2 之后?

最佳答案

std::move 将(非常量)右值引用作为参数。所以你不能将它直接绑定(bind)到 const 任何东西,无论是否为右值。所以在 (A) 和 (B) 中,当您调用 std::move 时,它会创建一个未命名的临时拷贝并 move 它。

因此,str 永远不会被 move ,也永远不会受任何影响。

要在不复制的情况下摆脱 const,您需要一个显式的 const_cast。如果你这样做,你会得到明显的未定义行为。

关于c++ - std::move 返回和输入引用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41265594/

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