Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: SFML 3.0 std::optional  (Read 4231 times)

0 Members and 1 Guest are viewing this topic.

Garwin

  • Jr. Member
  • **
  • Posts: 59
    • View Profile
SFML 3.0 std::optional
« on: July 29, 2024, 09:34:10 pm »
I have just looked at the main branch of SFML 3.0 and see that it uses std::optional.

However, it seems to me that implementation is done in a way that there are additional copies done as this way there is no RVO on return values. (see showVer1)
The relatively small change can correct this (see showVer2 or showVer3).
Practically instead of making object T and then returning object T, we need to create object std::optional<T> and return that object.

I have prepared an example on Godbolt.
https://godbolt.org/z/PTc39hMa8

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11032
    • View Profile
    • development blog
    • Email
Re: SFML 3.0 std::optional
« Reply #1 on: July 30, 2024, 01:52:18 pm »
Your comparison can be a bit misleading, since this isn't exactly about RVO and more about what type is constructed/returned.

The texture is moved in the first example, because it's moved into the optional.
It's not a failure of RVO, but a construction of a new optional instance with an existing type, which then needs to be moved.

If you want to look at RVO, you'll have to check what happens to the optional, as that's the return type and the one that can be RVO-ed.
I'd assume in all cases optional is optimized.

But it seems like a valid question, whether Texture::create should create a std::optional<Texture> from the start, instead of implicitly converting it when returning.

Note that the current implementation is not finalized and there are some open discussions regarding constructurs/loaders.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Garwin

  • Jr. Member
  • **
  • Posts: 59
    • View Profile
Re: SFML 3.0 std::optional
« Reply #2 on: July 30, 2024, 05:39:27 pm »
You are completely right about RVO. It is possible to see with updated example.
https://godbolt.org/z/PEWvjoYdW

Nevertheless, I would still create directly std::optional<T> instead of creating T and later return created std::optional<T>. This will save one construction and destruction of T.