简体   繁体   中英

How are temporary objects created and what's the actual operations that takes place?

Can anyone Explain how the output of this code is :

deleting 0xbfc69f7c  3,7
deleting 0xbfc69f84  2,4
deleting 0xbfc69f8c  1,3

Why aren't temporary objects destructor getting called which was created during the return from overloaded + operator. Is the Fraction object created inside the + function and its temporary copy are same and destructor is called just once, I guess that should not be the case. Can anyone explain what the actual operations that are taking place here.

Thanks in advance!

class Fraction{

    int num ; 
    int den ;
    public:
    Fraction( int x = 0  , int y = 0  ){ num = x ; den =  y ;  }
    Fraction( const Fraction & f ){

        cout<<"Copy Constructor for "<<f.num<<" , "<<f.den<<endl ;
        num = f.num ;
        den = f.den ; 

    }
    Fraction operator+( const Fraction& f) const{

        int x = f.num + num ; 
        int y = f.den + den  ;

        return Fraction(x,y) ; 

    }

    ~Fraction(){

        cout<<"deleting "<<this<<"  "<<num<<","<<den<<endl ; 

    }

};

int main() {

    Fraction f1(1,3);
    Fraction f2( 2, 4 );
    Fraction f3 = f1 + f2 ; 

    return 0;
}

It's because of return value optimization and copy elision (thanks to Joachim). The temporary object will be eliminated.

This line doesn't create a new Fraction and then copy it to f3 :

Fraction f3 = f1 + f2 ;

It initializes f3 with the contents of f1 and then the + operator is used to add f2 . No temporary object is created and deleted. Eg The copy constructor of Fraction is used instead of the assignment operator . A temporary object would be created and the assignment operator used in this case :

Fraction f3;
f3 = f1 + f2;

As others have pointed out, the compiler will optimize the use of the copy constructor and avoid (elide) the copy of f1 to f3 even if you build in debug mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM