C++ overloading operator, constant parameter or pass by value?

Viewed 188
template <typename T>
T operator+(T a, const T& b) {
    a += b;
    return a;
}

template <typename T>
T operator+(const T& a, const T& b) {
    T tmp {a};
    tmp += b;
    return tmp;
}

Is there any reason why you would pass argument as constant reference like the second function, over directly passing by value like the first function, since you need a temporary variable anyway?


Edit 1:

I think I should mention that these 2 functions alternative are just for handling case with lvalue arguments, and that I am to provide 2 other functions for handling with rvalue arguments, as follows.

template <typename T>
T operator+(T&& a, const T& b) {
    a += b;
    return std::move(a);
}

template <typename T>
T operator+(const T& a, T&& b) {
    b += a;
    return std::move(b);
}

So the emphasis of the question is, why would I need to explicitly create a temporary variable (function 2), when I can just let the language facilitate that automatically for me (function 1)?

1 Answers
template <typename T>
T operator+(T a, const T& b) {
    a += b;
    return a;
}

In here you are making a copy of variable a which is passed in here then you are updating a copy. which requires three copies to be created, and again you are returning by value.

template <typename T>
T operator+(const T& a, const T& b) {
    T tmp {a};
    tmp += b;
    return tmp;
}

in here your tmp variable has a local scope and variable a is const reference so no modification to the value of a is allowed. And you are returning a copy of temp which is a local variable.

Both work fine but the difference is in the number of copies created. you are making more copies in 1 st case than of the second.

Although the second one will be optimized for tmp variable to use move semantics in order to make fewer copies. so you will have faster performance in 2nd case

Related