c++ - 从返回 Boost 可选的函数返回右值引用

标签 c++ c++11 boost move-semantics boost-optional

从 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() or consume() 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 not const but good naming is important too

关于c++ - 从返回 Boost 可选的函数返回右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29114359/

相关文章:

c++ - 多个参数时移动构造函数

c++ - 在 C++、Ubuntu 中使用 BMP 文件

c++ - 那是 C++ 编译器错误吗?

c++ - 是否有开箱即用的功能来执行反向字符串分割器?

c++ - 在 C++/OpenCV 中从 DSLR 捕获实时视频

c++ - 将 vector<int*> 视为 vector<const int*> 而无需复制 (C++0x)

c++ - 在 ""运算符中从字符串转换为 const char* + size_t

c++ - 如何避免复制回调函数 (C++)

python - python 脚本完成后清除所有 c++ 对象

c++ - 如何实现动态线程Boost::Barrier?