Search code examples
c++rvalue-reference

Is it possible to return the current object if it is an r-value reference?


I have recently learned about r-value references. In order to more thoroughly experiment I decided to write a simple DenseMatrix class. My question is is it possible to write any function ( Transpose for this example ) such that for auto A = B.Transpose() separate matrix is returned, but for auto A = (B + C).Transpose() the result of the Transpose is calculated in place?


Solution

  • Yes, you can overload the Transpose member function on the ref-qualification of the object it's being called on:

    class DenseMatrix {
     
      DenseMatrix Transpose() const & {  // #1 called on l-values
         auto copy = *this;
         // transpose copy
         return copy;
      }
    
      DenseMatrix&& Transpose() && {  // #2 called on r-values
         // transpose *this
         return std::move(*this);
      }
    };
    

    So you get the result:

    B.Transpose();        // calls #1
    (B + C).Transpose();  // calls #2
    

    Here's a demo.

    Note that you could implement the l-value overload in terms of the r-value overload, like this:

    DenseMatrix Transpose() const & {  
      auto copy = *this;
      return std::move(copy).Transpose();
    }
    

    Here's a demo.