fc67
fc67

Reputation: 409

Operator Overloading without memory copies

Imagine we have the type A and we want to do the following operation:

A operator -(const A& a, const A& b)
{
    A c;

    //...

    return c;
}

When we call this operator, we do something like this:

A c;
c = a - b;

Basically we are allocating c twice (before the call to the operator and inside of the operator) and then copying its value to the variable on the main code, outside of the operator. In C, we can just pass the pointer to the functions and it will store them exactly where we want them without any intermediate allocation/copy:

void sub(A* a, A* b, A* c);

Is it possible to do the same with operator overloading or do I have to implement this as a C function to avoid that intermediate allocation/copy?

Thanks

Upvotes: 1

Views: 131

Answers (1)

Peter
Peter

Reputation: 36597

Before C++11, it depends on your compiler. The standards permit, but do not require, the compiler to eliminate (or elide) temporaries where the only way of detecting their existence is to track constructor and destructor calls. This is one case where that is permitted.

In C++-11, look up rvalue references for information on how to provide more of an assurance that temporaries will be elided.

Either way, it is not necessary to write a C function. C++ functions (for example, that accepts arguments by reference) are perfectly fine.

Upvotes: 1

Related Questions