Move Semantics and Pass-by-Rvalue-Reference in Overloaded Arithmetic

后端 未结 3 773
不思量自难忘°
不思量自难忘° 2021-02-13 21:01

I am coding a small numeric analysis library in C++. I have been trying to implement using the latest C++11 features including move semantics. I understand the discussion and to

3条回答
  •  终归单人心
    2021-02-13 21:38

    You should prefer overloading the operators as free functions to obtain full type symmetry (same conversions can be applied on the left and right hand side). That makes it a bit more obvious what you are missing from the question. Restating your operator as free functions you are offering:

    T operator+( T const &, T const & );
    T operator+( T const &, T&& );
    

    But you are failing to provide a version that handles the left hand side being a temporary:

    T operator+( T&&, T const& );
    

    And to avoid ambiguities in the code when both arguments are rvalues you need to provide yet another overload:

    T operator+( T&&, T&& );
    

    The common advice would be to implement += as a member method that modifies the current object, and then write operator+ as a forwarder that modifies the appropriate object in the interface.

    I have not really thought this much, but there might be an alternative using T (no r/lvalue reference), but I fear that it will not reduce the number of overloads you need to provide to make operator+ efficient in all circumstances.

提交回复
热议问题