从 Boost 1.56 开始,Boost optional 支持 move 语义。那么,下面的构造有意义吗?
boost::optional<SomeType> getValue()
{
if (value_available) { // value_available is a boolean
return std::move(value); // value is of type SomeType
} else {
return boost::none;
}
}
最佳答案
是的,这将是有意义的。这意味着您从 value
move 以防万一。
但是,令我惊讶的是,当看起来语义上该类已经包含一个可选值(value_available
是那个指示符)时,您返回可选值.
所以,我建议存储 value
作为optional<T>
已经并且只是返回那个
return value; // already optional!
在这种情况下,您可以免费获得正确的 move 语义和 RVO。当然如果value
不是本地的或临时的,你需要说
return std::move(value);
(Sidenote: I don't agree with the other answer that this is only useful if
getValue()
is called only once. If your type has a well-defined "default" state to return to after move, then it could become a sort of "1-element queue".)In such a case it might be nice to explicitly uninitialize the source value before returning. I think it is tricky to implement this exchange in an exception safe way though.
Consider renaming the function to e.g.
popValue()
,extractValue()
orconsume()
to explicitly mention the fact that using this function moves from internal object state. Of course, some warning is already implicitly present in the fact that the member function is notconst
but good naming is important too
关于c++ - 从返回 Boost 可选的函数返回右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114359/