c++ - 奇怪的移动分配运算符(operator)签名

标签 c++ pytorch rvalue-reference rvalue move-assignment-operator

我在 Pytorch 的张量后端遇到了一个不熟悉的移动赋值运算符签名(ATen, source )。 只是出于好奇,&& 是什么意思?运算符在末尾执行

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

虽然我熟悉移动语义以及通常的复制/移动构造函数和赋值运算符签名,但我在网上找不到任何有关上述语法的文档。

如果有人能解释这个运算符的作用、它与通常的移动赋值操作有何不同以及何时使用它,我将不胜感激。

最佳答案

用作表达式的类的对象可以是右值或左值。移动赋值运算符是类的成员函数。

本声明

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

表示为该类的右值对象调用此移动赋值运算符。

这是一个演示程序。

#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;
} 

程序输出为

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

这就是这个声明

    a = A();

赋值的左侧操作数是左值。

在此声明中

    A() = A();

赋值的左侧操作数是右值(临时对象)。

关于c++ - 奇怪的移动分配运算符(operator)签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554813/

相关文章:

c++ - 矩阵每一列的 eigen3 arraywise 矩阵 vector 乘积

c++ - InterlockedDecrement 使用 XADD 但 InterlockedIncrement 使用 INC?

c++ - 提供正确的 move 语义

c++ - GetModuleFileNameW 的转换错误

python - 如何将 HuggingFace 的 Seq2seq 模型转换为 onnx 格式

python - 运行时错误 : view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces)

python - 无法在 docker 中打开 jupyter notebook

c++ - 右值引用参数和模板函数

c++ - const T& 与 T&&

c++ - 使用 C++ notify_all() 避免饥饿