SFML community forums
General => SFML development => Topic started by: Garwin 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 (https://godbolt.org/z/PTc39hMa8)
-
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 (https://github.com/SFML/SFML/pull/3152) regarding constructurs/loaders.
-
You are completely right about RVO. It is possible to see with updated example.
https://godbolt.org/z/PEWvjoYdW (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.