Well i was working on return behavior of a function and i stuck up here. Well variable x2 inside f() is local hence it should be destroyed once function returns but it doesn't happens.
Also when function returns then there should be immediate call to copy constructor of class X but neither do this happen.. It seems as if x2 is created as static instead of local...
Also if u return x1 from f() then everything goes perfect...
I am not being able to figure out this behavior. Can anyone explain me why all this is happening?? I have put output of the following code below...
CODE:
#include <iostream>
using namespace std;
class X{
string name;
public:
X(){
cout<<"X()\n";
name="X()";
}
X(const X&){
cout<<"X(X&)\n";
name="X(X&)";
}
~X(){
cout<<"~"<<name<<" \n";
}
};
X f(X x1){ //2
cout<<"inside f()\n";
X x2;//3
cout<<"exiting f()\n";
return x2;
}
void g1(X&){
}
int main(){
X x1;//1
X x2=f(x1);
cout<<"exiting..\n";
}
OUTPUT:
X()
X(X&)
inside f()
X()
exiting f()
~X(X&)
exiting..
~X()
~X()
Aucun commentaire:
Enregistrer un commentaire