c++pytorchrvalue-referencervaluemove-assignment-operator

Strange Move Assignment Operator Signature


I came across an unfamiliar move assignment operator signature in Pytorch' tensor backend (ATen, source). Just out of curiosity, what does the && operator do at the end of

Tensor & Tensor::operator=(Tensor && rhs) &&

While I'm familiar with move semantics and the usual copy/move constructor and assignment operator signatures, I could not find any documentation online about the syntax above.

I would be grateful if someone could explain what this operator does, how it differs from the usual move assignment operation, and when it should be used.


Solution

  • Objects of a class used as expressions can be rvalues or lvalues. The move assignment operator is a member function of a class.

    This declaration

    Tensor & Tensor::operator=(Tensor && rhs) &&
    

    means that this move assignment operator is called for rvalue object of the class.

    Here is a demonstrative program.

    #include <iostream>
    
    struct A
    {
        A & operator =( A && ) &
        {
            std::cout << "Calling the move assignment operator for an lvalue object\n";
            return *this;
        }
    
        A & operator =( A && ) &&
        {
            std::cout << "Calling the move assignment operator for an rvalue object\n";
            return *this;
        }
    };
    
    int main() 
    {
        A a;
    
        a = A();
    
        A() = A();
    
        return 0;
    } 
    

    The program output is

    Calling the move assignment operator for an lvalue object
    Calling the move assignment operator for an rvalue object
    

    That is in this statement

        a = A();
    

    the left hand operand of the assignment is an lvalue.

    In this statement

        A() = A();
    

    the left hand operand of the assignment is rvalue (a temporary object).