I have been looking into this article about NRVO.
class RVO
{
public:
RVO(){
printf("I am in constructor\n"); }
RVO(const RVO& c_RVO) {
printf("I am in copy constructor\n"); }
~RVO(){
printf("I am in destructor\n"); }
int mem_var;
};
RVO MyMethod(int i)
{
RVO rvo;
rvo.mem_var = i;
return (rvo);
}
int main()
{
RVO rvo;
rvo=MyMethod(5);
}
The output is the following on visual studio and this is how i understand it
I am in constructor // main rvo construction
I am in constructor //MyMethod rvo construction
I am in copy constructor //temporary created inside MyMethod
I am in destructor //Destroying rvo in MyMethod
I am in destructor //Destroying temporary in MyMethod
I am in destructor //Destroying rvo of main
If instead i write the main as
int main()
{
RVO rvo = MyMethod(5);
return 0;
}
The output is the following and how understand it
I am in constructor //MyMethod rvo construction
I am in copy constructor //temporary created inside MyMethod
I am in destructor //Destroying rvo in MyMethod
I am in destructor //Destroying rvo of main
Why is temporary not destroyed in Mymethod
in the second version?
Why is copy constructor not called in RVO rvo = MyMethod(5);
.I think copy constructor should be called twice in second version, one for the temporary created inside Mymethod
and the other for RVO rvo = MyMethod(5);
I know some call may be getting elided.Can someone please help in explaining these calls.
EDIT:
Using return rvo
instead of return (rvo)
changes the output as
First case
I am in constructor
I am in constructor
I am in destructor
I am in destructor
second case
I am in constructor
I am in destructor
I guess when i removed the parenthesis, then NRVO kicks in.But i am more interested in the first output when there is no optimization