1
Matrix * Matrix::transpose()
{

    Matrix *m = new Matrix(*this->numCols, *this->numRows, false);

    for (int i = 0; i < *this->numRows; i++)
    {
        for (int j = 0; j < *this->numCols; j++)
        {
            m->setValue(j, i, this->getValue(i, j));
        }
    }

    return m;
}

Hello all. My memory keeps increasing after transposing matricies. How can i solve that, by deleting returned m(how to do it?) or deleting this->~Matrix() ?

  • 3
    The easiest thing to do would be to return a `Matrix` instead of a pointer to a newed object. – juanchopanza Jun 03 '18 at 19:31
  • Try this maybe: https://stackoverflow.com/questions/13223399/deleting-a-pointer-in-c – unholy_me Jun 03 '18 at 19:31
  • You guys are so fast thank you for answering me! I will try both of them. – Barbaros Baturay Jun 03 '18 at 19:33
  • Why are you using manual memory management and not smart pointers? – Jesper Juhl Jun 03 '18 at 19:34
  • @JesperJuhl i tried smart pointers but couldnt go far. I will try smart pointers too, should i use uniqe_ptr ? – Barbaros Baturay Jun 03 '18 at 19:36
  • 2
    @BarbarosBaturay No you don't need pointers of any type. Smart pointers aren't the solution when the problem is using dynamic allocation. The solution is to not use dynamic allocation. – juanchopanza Jun 03 '18 at 19:38
  • if you are ready to redesign the class *Matrix*, the best option will be *std::vector>*, as it provides dynamically contiguous memory allocation, and good to go, without bothering about the manual *delete*, like in your original case. – JeJo Jun 03 '18 at 19:55

1 Answers1

2

Just don't use any pointers. There is no reason to use new here. Just do

Matrix Matrix::transpose()
{

    Matrix m {*this->numCols, *this->numRows, false};

    for (int i = 0; i < *this->numRows; i++)
    {
        for (int j = 0; j < *this->numCols; j++)
        {
            m.setValue(j, i, this->getValue(i, j));
        }
    }

    return m;
}

Also another thing, why are you putting this everywhere? If you want to make clear something is a member, just prefix/postfix it like m_memberName, mMemberName or memberName_.

MivVG
  • 679
  • 4
  • 16