This Question arises from a Q&A here
I have some doubts that i think cant be asked in the followup comments there, and not too sure if i could have edited the linked question with my doubts...hence a new question.
Firstly,what i learnt from the linked question is that returning ref to local is EVIL!
Now,consider the same example from that question,a bit modified though:
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
class A
{
public:
int x;
string s;
A(int xx,string ss):x(xx),s(ss)
{
cout<<"A::A()"<<x<<","<<s<<"\n";
}
A(const A& that)
{
cout<<"cpy ctr\n";
x=that.x;
s=that.s;
}
A& operator=(const A& that)
{
cout<<"operator=\n";
}
~A()
{
cout<<"~A()"<<s<<"\n";
}
};
const A& getA1()
{
A a(1,"A1");
cout<<"returning from A1\n";
return a;
}
A& getA2()
{
A a(2,"A2");
cout<<"returning from A2\n";
return a;
}
A getA3()
{
A a(3,"A3");
cout<<"returning from A3\n";
return a;
}
int main()
{
A &newA2 = getA2(); //.....................LINE 2
cout<<"returned from A2\n";
cout<<"-----------------------------\n";
A newA3 = getA3(); //......................LINE 3
//A const newConstA3 = getA3 ();
cout<<"returned from A3\n";
cout<<"-----------------------------\n";
//cout<<"newA2="<<newA2.x<<","<<newA2.s<<"\n";
cout<<"newA3="<<newA3.x<<","<<newA3.s<<"\n";
}
The output is as follows..
A::A()2,A2
returning from A2
~A()A2
returned from A2
-----------------------------
A::A()3,A3
returning from A3
returned from A3
-----------------------------
newA3=3,A3
~A()A3
Now my doubts...
in LINE 2, the fun
getA2()
(which returns by ref) returns after destructing the temporary,so the recieving objectnewA2
is dangerous to use.(the reason why i have comented out its use.) so then why doesent the fungetA3()
destruct the temporary even though it returns by "copy" (Note that the temporary's destructor insidegetA3()
doesnt get called ever..onlynewA3
object's destructor gets called when it dies at the end ofmain()
)? I have no clue where does that temp go??Now if in LINE 2 i change it from
A& newA2 = getA2();
toA newA2 = getA2();
,the copy ctr gets called here(which eventually gives a segfault as the referent has died),but why doesnt the copy ctr gets called at LINE 3 ? How does the state of the temporary is getting copied into objectnewA3
,notice nooperator=()
is being called either ?Lastly.. the output here is from gcc, but does MSVC++2008 work differently?? As even for the code
A newA3 = getA3();
in LINE 3 it behaves the same as LINE 2,i.e, it destructs the temp before returning! any clues?