To pass and return — the story of functions, values and compilers
We heard it all, pass by const-reference if you intend to read, by value if you want to take. Return by … now, with
return it gets complicated. More often than not, it is return by value and hope for copy-elision to kick in. But is it really that simple? What about named objects or objects with non-trivial destructors? And does the magic also work if a return value is used in an assignment, or when there are multiple
return statements? On the second thought, why doesn’t copy elision work when passing arguments by value?
If those questions sound familiar to you, and you are still looking for the answers, do not despair. Together, we will look under the hood of optimisers, study the standards, and track objects that are passed to and returned from functions.
We’ll start with values and discover how compilers help us achieve optimal runtime behaviour by playing tricks with the stack or removing function calls altogether. We’ll see objects disappearing and multiple copies being avoided, even in tough scenarios. We’ll also find out that not all objects are created equal and not all compilers treat seemingly straightforward, standard-compliant code in the same way.
Dawid is a computer engineer with a heart for teaching. He's been programming for over 20 years evolving through Basic, Turbo Pascal and many other languages to finally find his home in the land of C++ (with occasional visits to C and Python). He teaches at Saxion University of Applied Sciences in the Netherlands, where he tries to convert new generations of programmers to use modern C++. Besides teaching, he uses C++ in the research on probabilistic state estimation for industrial applications. His interests focus on the design and evolution of programming languages and paradigms. In his free time he explores the evolving landscape of online teaching pedagogy or reads books.