Hi All!
I have the following code:
void Stack::operator =(Stack &rhs)
{
//do the actual copying
}
Stack::Stack(Stack &rhs) //copy-constructor
{
top=NULL; //initialize this as an empty stack (which it is)
*this=rhs; //invoke assignment operator
}
Stack& Stack::CopyStack()
{
return *this; //this statement will invoke copy contructor
}
It is being used like this:
unsigned Stack::count()
{
unsigned c=0;
Stack copy=CopyStack();
while (!copy.empty())
{
copy.pop();
c++;
}
return c;
}
Removing reference symbol from declaration of CopyStack (returning a copy instead of reference) makes no difference in visual studio 2008 (with respect to number of times copying is invoked). I guess it gets optimized away - normally it should first make a copy for the return value, then call assignment operator once more to assign it to variable sc.
What is your experience with this sort of optimization in different compilers?
Regards, Dženan