c++ - 将函数返回分配给堆的正确方法
问题描述
我定义了一个由 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;
}
解决方案
推荐阅读
- rust - 在 Rust 中计算素数
- javascript - 如何将图像保存在临时文件夹中
- java - 如何获取动态excelsheet的最后一列号?
- complex-numbers - 如何在 Q# 中将复数映射到量子位?
- xamarin - 应用程序退出时清除 CrossSecureStorage 属性
- c# - Unity Facebook 登录不适用于 Android 设备中的 Facebook 应用
- rust - 使用正确的参数验证该方法被调用了预期的次数
- python-3.x - 如何从 PyQt5 中显示的 excel 文件中删除数据并刷新
- mysql - 为什么会发生 pdo 异常?它显示找不到数据库驱动程序
- python - QRubberBand.geometry().intersects(???) 如何在 QGraphicsScene 中找到相交的图像?