gpt4 book ai didi

c++ - 返回时隐式 move std::optional 中包含的值

转载 作者:行者123 更新时间:2023-11-30 01:10:13 27 4
gpt4 key购买 nike

从 C++11 开始,我们有了 move 语义。在下面的示例中,将使用 move 构造函数(或复制省略),而不是 C++98 中的复制构造函数,无需任何额外的努力。

std::string f()
{
std::string res;
...
return res; // <- move is used here instead of copy
}

但是这个案例呢?

std::string f()
{
std::optional<std::string> res;
...
return *res; // <-- will the std::string value be moved??
}

还是必须写这样的东西?

std::string f()
{
std::optional<std::string> res;
...
return *std::move(res);
}

最佳答案

。隐式 move 的标准在[class.copy]中:

When [...], or when the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

*res 不是一个 id-expression,所以这条规则不适用。如果你想移出底层字符串,你必须明确地这样做:

return std::move(*res);
return *std::move(res);
return std::move(res).value(); // equivalent and possibly more legible

这些规则旨在仅在绝对安全的情况下尝试更有效的选择。如果您要返回一个自动存储持续时间变量,那么 move 它是绝对安全的,因为没有其他东西会再次引用该变量。

但如果您要返回 *res,则从那里 move 并不一定安全。如果这为您提供了某个外部对象的引用,该对象将比该函数更有效呢?我们会默默地离开我们期望仍然有效的状态!在这种情况下,由您作为用户声明您希望 move 它。

关于c++ - 返回时隐式 move std::optional 中包含的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617309/

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