Fandom

C Plus Plus

Returning rvalue

16pages on
this wiki
Add New Page
Talk0 Share
complex add_complex(const complex& a, const complex& b) {
   complex temp(a);
   temp.real += b.real;
   temp.imag += b.imag;
   return temp; // do copy constructor
}

Now considering, if the language can return the function value in Pascal style,

complex add_complex(const complex& a, const complex& b) {
   add_complex = a;
   add_complex.real += b.real;
   add_complex.imag += b.imag;
   return; // no need to do one more copy constructor
}

The variable with the same name as the function will be special variable which is the lvalue of the instance of temporary returned variable. Since the compiler can know which temporary variable to be returned ("add_complex" in this case), so the compiler can easily optimize the process, and no need to do unnecessary copy constructor.

Since the variable with the same name as the function is currently used as the function pointer, the alternate language syntax may be like,

complex add_complex(const complex& a, const complex& b) {
   temporary complex temp(a); // This is not an automatic local variable,
   temp.real += b.real;
   temp.imag += b.imag;
   return; // no need to do one more copy constructor
}

The "temporary" modifier is to tell that it is the temporary varible allocated outside this function (rather than to be a conventional automatic local variable). It is allocated just before entering the function, but not yet initialized by the constructor. It is constructed in the first declaration ("complex temporary temp(a);").

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.