Reputation: 103
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
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