4 ms·
I still don't really grok move semantics in C++ but is there a difference between assigning output to an out parameter and returning a value using std::move? Co
by thinkharderdev 5y ago
I still don't really grok move semantics in C++ but is there a difference between assigning output to an out parameter and returning a value using std::move? Conceptually they seem the same to me but from what little I understand std::move doesn't quite do what I think it does.
- jcelerier 5y agoYou must not use std::move when returning a value, just let RVO do its job. The compiler will make it so that the variable you are returning from your function will be constructed in-place at the variable you are assigning the function call to. However, if you are compiling at -O0 without any optimizations this may not happen.
- kaashif 5y agoSince 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.
- bergesenha 5y agoSince C++17 I believe this is guaranteed.
- jcranberry 5y agoThat only applies when you're returning a prvalue. NRVO isn't guaranteed: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58055 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58055