Return Value Optimization - C ++ - Destructor Calls

The following code calls the destructor 4 times:

#include<iostream>
using namespace std;

class A{
   public:
   A(){cout<<"A"<<endl;}
   ~A(){cout<<"~A"<<endl;}
   A f(){cout<<"F"<<endl; A b; return b;}
};

int main(){
   A a,b;
   b=a.f();
}

CONCLUSION:

A
A
F
A
~A
~A
~A
~A

Can someone explain? I thought there should only be three calls to the destructor.

+5
source share
6 answers

As main()there are two objects, so the destructor will be called two times only because of them. One object is in f(), so the destructor will be called one only because of it. Only 3 times (what do you expect, but read on ...)

, f. , RVO . RVO - , , , . RVO.

, ; , 3 .

+8

2 : A a,b;, f(): A b;, , b.

b , b , b, , .

A :

A(const A&) { cout << "copying" << endl; }

Destructor, , b f() b . , RVO/NRVO 3 .

RVO :

A a;
A b = a.f();

f() b. , 2 : A b, f().

, .

+3

. ?

, gcc:

A
A
F
A
~A
~A
~A
+1

A: f(), b. b main() .

+1

RVO. (, ).

Return value optimization is what the standard allows, but does not enforce.

Without optimization or O2, I also get 4 callse destructors.

With full optimization - Ox - I get only 3.

0
source

The local variable in is fcopied to a temporary variable when the function returns. This is why there are four calls to the destructor. (The copy operation calls the copy constructor A(A&), not your default constructor A(), so there are three As.)

0
source

All Articles