2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Jan Ca
  • 148
  • 6

1 Answers1

4

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • lvalues and rvalues are expressions, not objects . Objects can be automatic, static, dynamic, temporary etc. There is no such thing as "rvalue object". The ref-qualifiers relate to the value category of the expressions, not any property of the object that the expression designates. I mention this as the topic is commonly misunderstood , which is in some part due to sloppy use of terminology . – M.M Mar 05 '20 at 22:57
  • @M.M I meant objects used in expressions. – Vlad from Moscow Mar 05 '20 at 22:58