0

I've recently been reading a lot about rvalue references and move semantics. From all that I've seen the main applications for this are move constructors and move assignment operators. So I was asking myself, if you have a type that has got move constructor and move assignment operator implemented, if then it would be sensible to overload 'normal' functions with rvalues or if the move constructor/assignment operator of the used type are sufficient.

For example if we consider this code:

Image threshold(Image&& img){
    //will be called for rvalues
    //do something here that alters the image
    return img;
}

Image threshold(Image img){
    //this will be called for lvalues.
    //now we have a local copy of img so we can forward it as rvalue to the other one
    img = threshold(std::move(img));
    return img;
}

Now, we use it in this manner:

int main(){
    Image img("filename.png");
    Image img2;
    //here the lvalue function will be called
    img2 = threshold(img);

    //here the rvalue function should be called
    Image img3 = threshold(functionThatReturnsImage());
}

Would this way of overloading a function make sense? Or is it superfluous because the move constructor and asignment operator for the type Image are enough to make return by value more efficient (by moving instead of copying the return)?

Thank you for your help!

bweber
  • 3,772
  • 3
  • 32
  • 57
  • N.B: Image threshold(Image& img) would be called for lvalues – Christophe Dec 22 '14 at 17:20
  • No, it does not make sense. The second overload should accept by `const&` and directly pass a temporary copy. `auto threshold(const Image& img) {return threshold((Image)img); }` – Deduplicator Dec 22 '14 at 17:31
  • The 'duplicate' http://stackoverflow.com/questions/15600499/how-to-pass-parameters-correctly does not cover this question –  Dec 22 '14 at 17:55
  • The convenience function `Image threshold(Image img)` leads to ambiguity. Hover, with `Image threshold(const Image& img) { return threshold((Image)img); }` you almost get no benefit, you should avoid this kind of convenience. –  Dec 22 '14 at 18:05

0 Answers0