4 ms·
Since C++17, compilers are now required to elide copies and use RVO: https://en.cppreference.com/w/cpp/language/copy_elision https://en.cppreference.com/w/cpp/l
by kaashif 5y ago
Since C++17, compilers are now required to elide copies and use RVO: https://en.cppreference.com/w/cpp/language/copy_elision 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.
- jcelerier 5y agoThat'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 https://gcc.godbolt.org/z/jKPr98Mhx
- kaashif 5y agoIsn'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.
- jcelerier 5y agoYes, 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.
- deleted 5y ago[deleted]
- cyber_kinetist 5y agoOof, 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.
- jcelerier 5y agoFrom 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.