I didn't understand all of the output of the following code, i tried following a certain logic but still couldn't understand that output
#include<iostream>
using namespace std;
class X {
public:
X() { cout << "cons" << endl; }
~X() { cout << "decons" << endl; }
};
X* fun(X o)
{
X* xo = new X(o);
return xo;
}
X fun1(X const& o)
{
X oo;
return o;
}
int main()
{
X o;
X* xo = fun(o);
delete xo;
o = fun1(o);
return 0;
}
the output is :
cons
decons
decons
cons
decons
decons
decons
i understood the first line only
CodePudding user response:
When X
is constructed with no arguments, it emits cons
, but when it's constructed as a copy of another X
, then it doesn't emit anything.
X(const X&) {cout << "copy-cons"<< endl;}
Will add a lot of insight about the mystery Xs being destructed.
Here's your code with those points clearly labeled:
X* fun(X o) //copy-cons foo-o-param
{
X* xo = new X(o); //copy-cons fun-xo
return xo;
} //decons foo-o-param
X fun1(X const& o)
{
X oo; //cons fun1-oo
return o; //MAYBE copy-cons fun1-o-return
} //decons fun1-oo
int main()
{
X o; //cons main-o
X* xo = fun(o);
delete xo; //decons main-xo
o = fun1(o); //copy-assign, then MAYBE decons fun1-o-return
return 0;
} //decons main-o
And those are associated with this purely-theoretical explanatory output
cons main-o
copy-cons foo-o-param
copy-cons fun-xo
decons fun-o-param
decons main-xo
cons fun1-oo
copy-cons fun1-return
decons fun1-oo
(not logged, but copy-assign happens here)
decons fun1-return
decons main-o