开发者

returning an object (or a struct) in c++

开发者 https://www.devze.com 2023-01-18 10:25 出处:网络
hey, i got an question about what is going on in the next code: typedef struct { double re,im; } Complex;

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 开发者_Go百科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


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.


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


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


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


Also

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

Gotcha 58.

0

精彩评论

暂无评论...
验证码 换一张
取 消