Copy method optimization in compilers

Posted by Dženan on Stack Overflow See other posts from Stack Overflow or by Dženan
Published on 2010-04-03T15:10:04Z Indexed on 2010/04/03 15:13 UTC
Read the original article Hit count: 189

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

© Stack Overflow or respective owner

Related posts about c++

Related posts about containers