tags:

views:

137

answers:

5

hey, i got an question about what is going on in the next code:

 typedef struct {
      double re,im;
 } Complex;

 Complex ComplexCreate(double r=0.,doublei=0.)
 {
      Complex c;
      c.re=r;
      c.im=i;
      return c; // problem with this line 
      // my question is : is c getting duplicated and returning or does it return nothing
      // when i we go back to the main
 }

and i do know that in c++ i can and should use classes its just something that i want to understand for a test. thanks in advance for your help

+4  A: 

It will return a Complex object, but it may not make a copy either due to NRVO.

Fred Larson
+1  A: 

This can help you to understand mechanism: http://www.learncpp.com/cpp-tutorial/74a-returning-values-by-value-reference-and-address/

Patrice Bernassola
+3  A: 

C is going to be duplicated and you will get it. You can check it by yourself :

#include <iostream>


typedef struct T {
double a;
int b;
} T;


T f() {
    T newT = {10.0,5};
    std::cout << "Temporary address : " << &newT << std::endl;
    return newT;
}

int main(int argc,char* argv[]) {
    T retT = f();
    std::cout << "Final address : " << &retT << std::endl;
}

will usually produces different addresses like :

Temporary address : 0x7fff97d92660
Final address : 0x7fff97d926c0
Elenaher
+5  A: 

When no optimization is enabled, a copy of c will be made and returned. If Named Return Value Optimization (NRVO) is available the compiler may elide the copy.

Beyond that, why isn't complex a class with a constructor:

class Complex
{
public: 
    Complex( double r = 0.0, double i = 0.0 ) 
       : re( r ) 
       , im( i )
    {}

    double re;
    double im; 
};

Then, if you still needed a function like Complex ComplexCreate(double r=0.,doublei=0.) it would look like:

Complex ComplexCreate( double r= 0.0, double i = 0.0 )
{
    return Complex( r, i );
}

Returning an unnamed temporary variable here means compilers without Named Return Value Optimization (NRVO) will have a better chance to elide the copy of the local object - instead, working directly on the callers stack.

ceretullis
You could then totally eliminate the whole ComplexCreate by doing "Complex c( r, i );" :D
Goz
@Goz... obviously yes... but I really wanted to mention the use of unnamed temporary variables, and leaving the discussion in terms of ComplexCreate() seemed to be the path of least resistence.
ceretullis
A: 

Also

Stephen C.Dewhurst "C++ Gotchas. Avoiding Problems in Coding and Design"

Gotcha 58.

StNickolay