News for hackers. Stuff that matters.
Re:Care is needed to use C++ std:optional with non-trivial o... by kllrnohj on Friday January 13, 2023 @11:11AM (#34369764)
https://en.cppreference.com/w/cpp/utility/optional/value_or

value_or's parameter type is U&&, so no there's no additional copy there. There's only the explicitly visible default constructor call.

But you did get me to take a second look at the post, and yeah the author's statement of "Finally, we copy construct an instance of A when the call to value_or terminates." is just incorrect. Try it out yourself: https://godbolt.org/z/hWqnrfGKE

If you replace the `.value_or(A())` with `.value()` there's no reduction in copies, only a single reduction in the constructed count which of course makes sense since the `A()` parameter isn't there.

The way you would optimize this to eliminate copies would be to do things like construct the optional in-place and take the parameter by const& instead, such as:

   A f(const std::optional<A>& z) {
      return z.value_or(A());
   }

   A g() { 
      std::optional<A> z(std::in_place, "message"); 
      return f(z); 
   }
`std::in_place` being definitely a classic C++ "quirk" here and usually unlikely to be worth it but hey if you want to play "minimize the copy count" golf there you go. The value_or isn't actually adding any copies, though.

There are no comments on this comment yet.