0

I've defined a matrix class consisting of a float** and an assignment operator. I would like to now the proper way to allocate a member of this class onto the heap, where the member is returned from a function. In function A I calling function B, which returns a matrix to function A. However, this matrix gets deleted before function A returns. Any help would be greatly appreciated.

mat broadcast(list a, list b); // function B

mat function A(){
  mat *j = new mat(1, 1); // trying to allocate on heap
  *j = broadcast(j1, j0); 
  //both *j and the rvalue broadcast are inexplicably deleted here
  return j;
}

Assignment operator:

 mat &operator=(const mat &other) {
    clear(); //deletes any previous memory

    this->arr = new float *[other.row_size];
    for (int i = 0; i < other.row_size; i++) {
      arr[i] = new float[other.col_size];
    }
    for (int i = 0; i < other.row_size; i++) {
      for (int j = 0; j < other.col_size; j++) {
        arr[i][j] = other.arr[i][j];
      }
    }
    return *this;
  }
  • You must correctly implement a copy constructor and an assignment operator (at the very least, and a move constructor and a move assignment operator for extra credit and brownie points). See the linked question for more information. – Sam Varshavchik May 24 '20 at 16:41
  • Sam, just added my copy constructor. – Eddie Zhang May 24 '20 at 16:43
  • 1
    No, you added an assignment operator. You failed to mention that in your original question. Therefore, if you do have a copy constructor and an assignment operator defined, but there still seems to be a memory management issue, then your next step is to use your debugger to figure out why. This is what a debugger is for. – Sam Varshavchik May 24 '20 at 16:45

0 Answers0