mardi 21 novembre 2023

How can an object find that is rvalue reference(unnamed value) in C++? [duplicate]

I have a class named Matrix. I want overload operator ! that return transpose of matrix. When the main matrix is a unnamed object I prefer to use it's allocated memory to construct transpose matrix, otherwise use new matrix. How can I do this.(We assume that the number of rows and columns of the matrix is ​​equal)

class Matrix {
// ...
/* transpose of a unnamed matrix */
Matrix&& operator !() 
{
    for (int i = 0; i < rows_; ++i)
        for (int j = 0; j < cols_; ++j)
            std::swap(data[i][j],data[j][i]);
    return std::move(*this);
}

/* transpose of a matrix that is not rvalue refrence */
Matrix operator !()const
{
        Matrix ret(cols_, rows_);
    
        for (int i = 0; i < rows_; ++i)
            for (int j = 0; j < cols_; ++j)
                ret.data[j][i] = data[i][j];
        return temp;
}
};

The compiler does not allow me to have both overload together.

Aucun commentaire:

Enregistrer un commentaire