Since C++17, compilers are now required to elide copies and use RVO: https://en.cppreference.com/w/cpp/language/copy_elision
There are probably exceptions and loopholes just like with literally everything in C++, but there's this line:
> Return value optimization is mandatory and no longer considered as copy elision; see above.
That's only in the unnamed case. Here's a simple case than GCC does not optimize even in -std=c++20 (and even at -O3 LOL): https://gcc.godbolt.org/z/jKPr98Mhx
Isn't it kind of confusing that RVO is mandatory, but it turns out RVO only refers to unnamed RVO and not NRVO? I would've thought that since NRVO is a type of RVO...
Thanks for the clarification. Clang does do NRVO in that case but I guess it's obviously not guaranteed by the standard.
Yes, I believe that explicitly qualifying unnamed and named rvo should be the norm and would clarify a lot of confusion on these topics.
I guess it makes sense that an optimization that GCC is not able to do at all should not be part of the standard ; I'm pretty sure it should be possible to write cases that clang wouldn't be able to optimize either.
Re:Const all the things?
by cyber_kinetist on Monday January 24, 2022 @12:41PM
(#30061045)
Oof, that’s a bit painful. I thought you could rely on NRVO for recent versions of gcc and clang, but feel I should be a lot more careful after seeing that example.
From what I could see through hundreds of godbolt snippets, if you declare the variable you'll return at the very top of the function before any control flow, NRVO will pretty much always happen.
Re:Const all the things?
by jcranberry on Monday January 24, 2022 @05:13PM
(#30064804)
That only applies when you're returning a prvalue. NRVO isn't guaranteed: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58055
Re:Const all the things?
by bergesenha on Monday January 24, 2022 @09:55AM
(#30058315)
Since C++17 I believe this is guaranteed.
However, if you are compiling at -O0 without any optimizations this may not happen.