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() ?

7
  • 3
    The easiest thing to do would be to return a Matrix instead of a pointer to a newed object. Commented Jun 3, 2018 at 19:31
  • Try this maybe: stackoverflow.com/questions/13223399/deleting-a-pointer-in-c Commented Jun 3, 2018 at 19:31
  • You guys are so fast thank you for answering me! I will try both of them. Commented Jun 3, 2018 at 19:33
  • Why are you using manual memory management and not smart pointers? Commented Jun 3, 2018 at 19:34
  • 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. Commented Jun 3, 2018 at 19:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Well, thank you for advice. Also i did somethink like void transpose and changing the values if the rows or cols are the same etc. Is it an efficient way ?
Matrix m(*this->numCols, *this->numRows, false);
Yes, that's even better. Editing now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.