c++c++14

Return content of optional


I have a function that returns a value from an internal optional.

T foo() {
  std::optional<T> v;
  ...
  return *v;
}

What's the most efficient way to return *v?

  1. return *v
  2. return *std::move(v)
  3. return std::move(*v)

I am leaning towards 3, but would like to get some clarity...


Solution

  • Option 1 has the worst performance as it will always do a copy. This is because the return type and v are different types so there is no way NRVO can be applied so the lvalue T that *v yields will be copied into the return object.

    Options 2 and 3 do the same thing, they both yield an rvalue T so both options will cause a move to happen. I prefer option 3 since return std::move(*v) looks more like returning an rvalue than return *std::move(v) does because of the external dereference.