Each time that an argument is passed by value, or returned by value, two important methods are called:
The copy is temporary stored in the function stack.
This is extremely inefficient. The following steps could be avoided just passing by reference:
The following code highlight what the compiler is silently calling to implement the “by value” behaviour:
#include <iostream> using namespace std; class Dummy { public: Dummy() { cout << "Dummy()" << endl; } Dummy(const Dummy& rhs) : a(rhs.a) { cout << "Dummy(const Dummy& rhs)" << endl; } Dummy& operator=(const Dummy& rhs) { cout << "Dummy& operator=(const Dummy& rhs)" << endl; a = rhs.a; return *this; } ~Dummy() { cout << "~Dummy()" << endl; } int a; }; Dummy get_dummy(void) { cout << "> Dummy get_dummy(void)" << endl; Dummy test; test.a = 1; return test; } bool pass_dummy(Dummy d) { cout << "> void pass_dummy(Dummy d)" << endl; return (d.a == 1); } int main() { cout << "== Test return by value ==" << endl; Dummy t; t = get_dummy(); cout << "\n== Test pass by value ==" << endl; pass_dummy(t); cout << "\n== End ==" << endl; return 0; }
== Test return by value == Dummy() > Dummy get_dummy(void) Dummy() Dummy& operator=(const Dummy& rhs) ~Dummy() == Test pass by value == Dummy(const Dummy& rhs) > void pass_dummy(Dummy d) ~Dummy() == End == ~Dummy()