4 ms·
The best way to tell is to try it the modern way and then look at the assembly code generated on something like godbolt.org. If it ends up being less efficient
by daemin 7y ago
The best way to tell is to try it the modern way and then look at the assembly code generated on something like godbolt.org. If it ends up being less efficient then you change it to accept a non-const reference to store the result in as a parameter instead.
Though if you'll be calling the same function repeatedly to accumulate content into a single container it is far more efficient to have a function with an output reference rather than returning a new container. This will result in fewer memory allocations and you can also pre-allocate the size once before calling those functions.
On the part of tooling it might be nice if there was a way to annotate a function so that it creates a warning if the compiler cannot use copy-elision for the return value. (To be honest I haven't checked the documentation for this specific thing)
- gpderetta 7y agoCopy elision is now mandated in many (but not all) cases FWIW.
- daemin 7y agoThe warning that I would want would trigger when someone changes the function and prevents or suppresses copy elision from happening. Like for example adding a check at the start of the function and returning a default container.
- gpderetta 7y agomaking the returned object non copyable, non movable is a an option. edit: also, the rule is simple: RVO is always mandated, NRVO remains an optimization.
- daemin 7y agoI'm not sure if C++14 or C++17 has fixed this but if the object was not copy-constructible then the compiler would emit an error if it was returned by value even if RVO/NRVO was meant to be used. I figure because semantically you need to enable copy-construction of the object.
- gpderetta 7y agoIIRC it was changed in C++14. Now in the RVO case, no copy/move constructor is required (and in fact the compiler is not allowed to call it if it exists).