0

The following slides contrast patterns of "old school" and "modern" C++. http://klmr.me/slides/modern-cpp.pdf

Instead of writing

huge_object* build_new_object() {
   huge_object* ret = new huge_object;
   …
   return ret;
}

they advise to write

huge_object build_new_object() {
   huge_object ret;
   …
   return ret;
}

I understand that the first code snippet is bad because we have to remember to delete the huge_object, and it's not exception-safe.

But doesn't the second snippet have the disadvantage of leading to an expensive copy ctor call? Wouldn't return by smart pointer be much better than return by value?

Tarvoc
  • 83
  • 5
  • 6
    No, the compiler will use copy elision. Search for "Return value optimization". – Jodocus Sep 17 '17 at 12:18
  • Is `sizeof(huge_object)` huge or is `ret.size()` huge? Because the solution in the first case if the add a level of indirection that takes you to the second case, and return `std::unique_ptr`. – StoryTeller - Unslander Monica Sep 17 '17 at 12:19
  • 2
    With modern compilers, there won't be a copy-constructor call. The compiler is not required to, but is permitted to avoid the needless object copy, and most modern compilers, in practice, implement this optimization. – Sam Varshavchik Sep 17 '17 at 12:19
  • 1
    Also: [What are move semantics?](https://stackoverflow.com/questions/3106110/what-are-move-semantics) –  Sep 17 '17 at 12:23
  • 1
    @ Sam Varshachik When returning a prvalue (that is, a nameless value) it is actually mandatory for a C++17 compiler to omitt any calls to copy or move constructors. In contrast to returning glvalues, they don't even have to be accessible. See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html – Jodocus Sep 17 '17 at 12:27

0 Answers0