首页 > 解决方案 > 将函数返回分配给堆的正确方法

问题描述

我定义了一个由 float** 和赋值运算符组成的矩阵类。我现在想以正确的方式将此类的成员分配到堆上,该成员是从函数返回的。在函数 AI 调用函数 B 中,该函数将一个矩阵返回给函数 A。但是,该矩阵在函数 A 返回之前被删除。任何帮助将不胜感激。

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;
}

赋值运算符:

 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;
  }

标签: c++memory-managementmemory-leaks

解决方案


推荐阅读