Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

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

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)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...