Sunny Shah
Sunny Shah

Reputation: 111

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;
}

Upvotes: 4

Views: 75

Answers (2)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22264

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. E.g. 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.

Upvotes: 1

Xiaotian Pei
Xiaotian Pei

Reputation: 3260

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

Upvotes: 4

Related Questions