Emy eminescu
Emy eminescu

Reputation: 103

C++ - Destructor is called more times than expected

Consider the following piece of code:

class C1
{   public:

        C1(){ cout<<"CONSTR WAS HERE"<<endl; }

        C1(const C1&ob){ cout<<"COPY CONSTR WAS HERE"<<endl; }

        ~C1(){ cout<<"DESTR WAS HERE"<<endl; }
}

void f1(C1 x){  }

int main()
{
    C1 c1;
    f1(c1);
}

If we run the code as it is, we get:

CONSTR WAS HERE
COPY CONSTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE

Which is perfectly understandable from my point of view. However, if we modify the function "f1" to:

C1 f1(C1 x){ }

instead of

void f1(C1 x){ }

we get:

CONSTR WAS HERE
COPY CONSTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE

and I am not quite sure why.

Upvotes: 3

Views: 185

Answers (2)

Vittorio Romeo
Vittorio Romeo

Reputation: 93364

Enable your warnings:

warning: no return statement in function returning non-void [-Wreturn-type]

You have undefined behavior in your program, which means that anything can happen. The compiler is likely "returning an undefined instance of C1 here", which causes the destructor to be called.

The program might crash or do anything else depending on your compiler/flags/machine.

Upvotes: 12

AndyG
AndyG

Reputation: 41220

Modify C1 f1(C1 x){} to actually return something and your output will be as expected (Demo)

C1 f1(C1 x){ return {};}

CONSTR WAS HERE
COPY CONSTR WAS HERE
CONSTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE
DESTR WAS HERE

Otherwise your code exhibits undefined behavior.

Upvotes: 9

Related Questions