通过move赋值实现B=f(A)语法

Implementing the B=f(A) syntax by move assignment

本文关键字:语法 move 赋值 实现 通过      更新时间:2023-10-16

我已经实现了一个矩阵类与移动赋值

template <typename OutType>
class Matrix
{
    public:
        int Rows_;                      // number of Rows
        int Columns_;                   // number of Columns
        OutType *data_;                 // row Major order allocation
    // STUFF
        Matrix<OutType> & operator=(Matrix<float>&& other) {
            swap(other);
            return *this;
        }
        void swap(Matrix<float>& other) {
            int t_Rows_ = Rows_;        Rows_ = other.Rows_;        other.Rows_ = t_Rows_;
            int t_Columns_ = Columns_;  Columns_ = other.Columns_;  other.Columns_ = t_Columns_;
            float* t_ptr = data_;
            data_ = other.data_;
            other.data_ = t_ptr; }      
}

来实现B=f(A);语法,如

中所建议的

c++:实现B=f(A), B和A数组和B已经定义

作为可能的函数,我正在考虑FFT,实现为

Matrix<float> FFT(const Matrix<float> &in)
{
    Matrix<float> out(in.GetRows(),in.GetColumns());
    // STUFF
    return out;
}

是否有进一步提高效率的空间?是否有进一步的技巧来改进,例如,移动分配或swap函数?

编辑:KONRAD RUDOLPH注释后的新解

        Matrix & operator=(Matrix&& other) {
            std::swap(Rows_, other.Rows_);
            std::swap(Columns_, other.Columns_);
            std::swap(data_, other.data_); 
            std::cout << "move assigned n";
            return *this;
        }

我建议为您的类实现move-assignment和move-construction:

Matrix( Matrix<OutType> &&that ) noexcept
    : Rows_(that.Rows_)
    , Cols_(that.Cols_)
    , data_(that.data_)
{
    that.Rows_ = that.Cols_ = 0;
    that.data_ = nullptr;
}
Matrix<OutType> &operator=( Matrix<OutType> &&that ) noexcept {
     using std::swap;
     swap( Rows_, that.Rows_ );
     swap( Cols_, that.Cols_ );
     swap( data_, that.data_ );
     return *this;
}

如果你实现这样的移动操作(构造和赋值),std::swap应该为你的代码工作得很好,你不需要提供你自己的。如果您确实想提供自己的swap实现,我建议将其作为两个参数的friend函数提供,以便可以通过参数依赖查找找到它。我还建议调用swap(和所有其他函数)时不考虑名称空间限制,如上所示,这样ADL就不会被抑制(除非,由于某种原因,您确实需要指定调用哪个函数,并且为特定类型定制的重载是错误的)。在处理模板化代码时,ADL特别有价值。如果使用std::限定符调用std::swap,就会大大减少用户定义类型提供更有效交换实现的机会。