This is what i believe:
When a function returns it make a new temporary copy of the object and this temp object remains in memory for the time of the statement from where it was called.
when a function returns reference that object is itself returned. This means that that object should not be local.
so when i do this:
MyStruct & ReferenceReturn(MyStruct cl)
{
return cl;
}
in main() i do
MyStruct d("notmyname"),g("myname");
d = ReferenceReturn(g);
cout << d.name;
cout << ReferenceReturn(g).name;
It prints garbage in both.
What gets returned ? : reference to local copy of g i.e. cl which gets destroyed as soon as function is finished or a reference to temporary object that gets destroyed after the statement is over. But since if temp would have been created it would have overritten d in the right way. So i believe that it is the reference of localcopy of passed value that is getting returned .
But as soon as i made destructor in the struct it went perfectly, with following code and specific output.
~MyStruct()
{
cout << name << " is destroying";
}
Output:
myname is destroying
myname
myname
myname is destroying
....
This output shows that only one object is created for each call. (there are two calls)
But why it is not working without destructor ?
Thanks
Create
temporary object, assign it tocl, returnreferenceto object, destruct object. So, it’sdangling reference. Compiler can usecopy-elisionand don’t copy object, but can not… Use something lile