I
ibm
I am running a simple test
/*******CODE************/
class A
{
int _x;
public:
A(int i)
{
_x = i;
printf("A %d\n", _x);
}
A(const A& a)
{
_x = a._x;
printf("CopyA %d\n", _x);
}
~A()
{
printf("~A %d\n", _x);
}
};
A& f1()
{
A a(1);
return a;
}
A& f2()
{
return A(2);
}
A f3()
{
A a(3);
return a;
}
A f4()
{
return A(4);
}
int _tmain(int argc, _TCHAR* argv[])
{
A a1 = f1();
A a2 = f2();
A a3 = f3();
A a4 = f4();
printf("destroying all\n");
return 0;
}
/*******OUTPUT**********/
A 1
~A 1
CopyA -85899346 //copycon for 1
A 2
~A 2
CopyA -85899346 //copycon for 2
A 3
CopyA 3 //copycon for 3
~A 3
A 4 //copycon for 4
destroying all
~A 4
~A 3
~A -858993460
~A -858993460
-------------------------
This output is very much understandable bcz the rule is never return a
local reference from a function.
Now I remove the copy constructor from the code and get the following
ouput
/******OUTPUT with copycon ***********/
A 1
~A 1
A 2
~A 2
A 3
~A 3
A 4
destroying all
~A 4
~A 3
~A 2
~A 1
--------------------------------
Q1, if the rule "never return a local reference from a function"
remains intact than is this ( ~A 2, ~A 1 after destroying all )
something to do with how VC++ compiler is handling it. Also I think in
some compilers returning a reference from a function returns a compiler
error.
Q2, Why in both the codes a destructor for A 4 is not called before
destroying all statement that is how exactly is A a;return a;
differnt from return A;
thanks
/*******CODE************/
class A
{
int _x;
public:
A(int i)
{
_x = i;
printf("A %d\n", _x);
}
A(const A& a)
{
_x = a._x;
printf("CopyA %d\n", _x);
}
~A()
{
printf("~A %d\n", _x);
}
};
A& f1()
{
A a(1);
return a;
}
A& f2()
{
return A(2);
}
A f3()
{
A a(3);
return a;
}
A f4()
{
return A(4);
}
int _tmain(int argc, _TCHAR* argv[])
{
A a1 = f1();
A a2 = f2();
A a3 = f3();
A a4 = f4();
printf("destroying all\n");
return 0;
}
/*******OUTPUT**********/
A 1
~A 1
CopyA -85899346 //copycon for 1
A 2
~A 2
CopyA -85899346 //copycon for 2
A 3
CopyA 3 //copycon for 3
~A 3
A 4 //copycon for 4
destroying all
~A 4
~A 3
~A -858993460
~A -858993460
-------------------------
This output is very much understandable bcz the rule is never return a
local reference from a function.
Now I remove the copy constructor from the code and get the following
ouput
/******OUTPUT with copycon ***********/
A 1
~A 1
A 2
~A 2
A 3
~A 3
A 4
destroying all
~A 4
~A 3
~A 2
~A 1
--------------------------------
Q1, if the rule "never return a local reference from a function"
remains intact than is this ( ~A 2, ~A 1 after destroying all )
something to do with how VC++ compiler is handling it. Also I think in
some compilers returning a reference from a function returns a compiler
error.
Q2, Why in both the codes a destructor for A 4 is not called before
destroying all statement that is how exactly is A a;return a;
differnt from return A;
thanks