News for hackers. Stuff that matters.
Re:Const all the things? by kaashif on Monday January 24, 2022 @09:54AM (#30058303)
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.

Re:Const all the things? by jcelerier on Monday January 24, 2022 @10:31AM (#30058844)
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
Re:Const all the things? by kaashif on Monday January 24, 2022 @01:26PM (#30061722)
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.

Re:Const all the things? by jcelerier on Monday January 24, 2022 @01:52PM (#30062131)
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.
Re:Const all the things? by jcelerier on Tuesday January 25, 2022 @05:09PM (#30078818)
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.