Correctly propagating a `decltype(auto)` variable from a function

That’s the simplest and most clear way to write it: template <typename F> auto invoke_log_return(F&& f) { auto result = f(); std::printf(” …logging here… %s\n”, result.foo()); return result; } The GCC gets the right (no needless copies or moves) expected result: s() in main prvalue s() …logging here… Foo! lvalue s(const s&) …logging here… Foo! … Read more

Exact moment of “return” in a C++-function

Due to Return Value Optimization (RVO), a destructor for std::string res in make_string_ok may not be called. The string object can be constructed on the caller’s side and the function may only initialize the value. The code will be equivalent to: void make_string_ok(std::string& res){ Writer w(res); } int main() { std::string res(“A”); make_string_ok(res); } That … Read more

Return value optimization and copy elision in C

RVO/NRVO are clearly allowed under the “as-if” rule in C. In C++ you can get observable side-effects because you’ve overloaded the constructor, destructor, and/or assignment operator to give those side effects (e.g., print something out when one of those operations happens), but in C you don’t have any ability to overload those operators, and the … Read more

How does guaranteed copy elision work?

Copy elision was permitted to happen under a number of circumstances. However, even if it was permitted, the code still had to be able to work as if the copy were not elided. Namely, there had to be an accessible copy and/or move constructor. Guaranteed copy elision redefines a number of C++ concepts, such that … Read more

What are copy elision and return value optimization?

Introduction For a technical overview – skip to this answer. For common cases where copy elision occurs – skip to this answer. Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. It makes returning by value or pass-by-value feasible in practice (restrictions apply). It’s the only … Read more

tech