jeudi 31 janvier 2019

Why would temporary lifetime extension cause destructor to be called multiple times?

Consider the following snippet:

#include <iostream>

using namespace std;

class Temp {
    public:
    Temp() { cout << "Temp()" << endl;}
    ~Temp() { cout << "~Temp()" << endl;}
};

Temp GetTemp() {
     cout << "GetTemp" << endl;
    return Temp();
}

Temp TakeTemp(Temp temp) {
    cout << "TakeTemp" << endl;
    return temp;
}


int main()
{
    TakeTemp(GetTemp());

    return 0;
}

When I ran TakeTemp(GetTemp());, the output looks like

GetTemp                                                                                                                                                        
Temp()                                                                                                                                                         
TakeTemp                                                                                                                                                       
~Temp()                                                                                                                                                        
~Temp()     

Note that ~Temp() is called twice here (but only 1 temp obj is constructed). This seems odd since 1) the temp variable returned by GetTemp() is supposed to have its lifetime extended to the full expression, and 2) since we return temp directly in TakeTemp, return value optmization will reuse the same object.

Can anyone explain why there are multiple dstor calls here?

(Note that if we place more layers of TakeTemp() around, the number of dstor calls grows proportionally.)

Aucun commentaire:

Enregistrer un commentaire