Dženan
Dženan

Reputation: 3395

Copy method optimization in compilers

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

Upvotes: 1

Views: 316

Answers (3)

themoondothshine
themoondothshine

Reputation: 3041

I guess what you're looking for is RVO (Return Value Optimization) and NRVO (Named Return Value Optimization). Compiler optimization is a vast subject, and if I were to start typing a description it would take toooo long! Just check out this blog post... It explains it nicely.

Upvotes: 0

baris.aydinoz
baris.aydinoz

Reputation: 1950

If I understand correctly, you can prototype your stack objects and return prototypes instead, which may introduce some performance but you have to be careful about object ownership for memory resources.

You can use Prototype Factory design pattern, if you like.

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 791849

This statement is copy-initialization of a Stack called copy from the return value of CopyStack(). There's no assignment.

Stack copy=CopyStack();

In this function the comment is incorrect. There is no invocation of the copy-constructor as the return value is a reference.

Stack& Stack::CopyStack()
{
    return *this; //this statement will invoke copy contructor
}

This means that the original initialization is, in effect, copy-construction from *this variable.

If the return value was by value then the copy-initialization would be from a temporary, but one which could validly be eliminated by the compiler.

I don't see the point in the CopyStack function. It would be more idiomatic to just perform a direct initialization:

Stack copy(*this);

Upvotes: 2

Related Questions