Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Arithmetic Operator without new return object

Tags:

c++

This is a rather simple concept. I have an arithmetic operator and I wish for the operation to update not create an object. Essentially,

MyType A;
MyType B;
MyType C;

A = B - C;
A = C - B;

The statement A = B - C should not call the constructor for MyType again since A is already created, i.e. the constructor should only be called 3 times in this program. Is there some way to achieve this while maintaining a nice syntax? I suspect that I could let the operator function know not to create an object but rather to use some reference. Is there a more streamlined way to do this using some c++ syntax unknown to me?

class MyType
{
    MyType* OperatorReturnObj;

    MyType operator-(const MyType& Left, const MyType& Right)
    {
        // This removed and replaced with SetOperatorReturnObj function
        // MyType OperatorReturnObj();

        OperatorReturnObj= Left - Right;
        return OperatorReturnObj;
    }


    void MyType SetOperatorReturnObj(MyType* Ref)
    {
         OperatorReturnObj = Ref;
    }
};
like image 619
Russell Trahan Avatar asked Dec 05 '25 10:12

Russell Trahan


1 Answers

Without ugly tricks like creating pool of objects and using them internally (where complications would be more expensive than any benefits for this case), there is no way to achieve this. Problem is that statement:

A = B - C;

is equal to:

A.operator=( operator-( B, C ) );

as you can see operator-( B, C ) has to be executed first and provide result somewhere. So you either have to change syntax like:

A += B; A -= C; // or even
(A += B) -= C; // or maybe
A += B -= C; 

or use regular syntax and if you need efficiency implement move semantics.

After some thought you can create object of type MyTypeExression which does not do actual calculations but remember arguments and operations and only do them later when MyType::operator=(MyTypeExression) is executed. Though for that to work you probably need a wrapper with smart pointer for MyType so MyTypeExression does not have to copy it's arguments. So this solution can be considered as complicated trick I mentioned before.

like image 174
Slava Avatar answered Dec 07 '25 23:12

Slava