c++ - 重载包含 if 语句的运算符时析构函数无法正常工作
问题描述
我在 C++ 模板的帮助下为矩阵运算创建了一个抽象数据类型。这是该类的代码如下
template <typename item_type>
class matrix
{
private:
item_type **data;
public:
size_t *shape;
matrix(size_t n_rows, size_t n_cols)
{
// allocates a memory block of item_type of size n_rows by n_cols and initializes it with zeros and allocates memory for shape array and saves n_rows in shape[0] and n_cols in shape[1].
}
~matrix()
{
for (size_t i = 0; i < this->shape[0]; i++)
{
free(data[i]);
}
free(this->data);
free(this->shape);
}
代码非常标准,包含一个构造函数和一个析构函数。当我像这样重载运算符'+'时,代码可以正常工作。
friend matrix<item_type> operator+(matrix<item_type> m1 ,matrix<item_type> m2)
{
matrix<item_type>res(m1.shape[0] , m1.shape[1]);
for (size_t i = 0; i < m1.shape[0]; i++)
{
for (size_t j = 0; j < m1.shape[1]; j++)
{
res[i][j] = m1[i][j] + m2[i][j];
}
}
return res;
}
正如预期的那样,代码工作得很好,并给出了预期的结果,但是当我用 if 条件重载运算符'+'时:
friend matrix<item_type> operator+( matrix<item_type> m1, matrix<item_type> m2)
{
if (m1.shape[0] == m2.shape[0] && m1.shape[1] == m2.shape[1])
{
matrix<item_type> res(m1.shape[0], m1.shape[1]);
for (size_t i = 0; i < m1.shape[0]; i++)
{
for (size_t j = 0; j < m1.shape[1]; j++)
{
res[i][j] = m1[i][j] + m2[i][j];
}
}
return res;
}
else
{
// try to broadcast etc...
}
}
返回的矩阵包含形状数组和数据数组中的垃圾值。但是当我删除析构函数时,两个代码都可以正常工作。我对此的理解是,甚至在第二种情况下返回 res 之前,析构函数就被调用了。我希望第二个代码在析构函数也能正常工作的情况下正常工作。我在这里做错了什么???
解决方案
推荐阅读
- javascript - 在 Typescript 中仅接受字符串密钥对值的通用对象
- html - 如何对齐 DIV 以创建一个看起来像搜索框的框
- reactjs - 在 React TypeScript 中循环遍历整个 div
- php - 使用 json_encode 将值从 PHP 传递到 Ajax 时出现意外结果
- python - 我想从bubble_list 中提取menu_header,然后只需要从menu_list 中提取条件类型='menu' 的所有标题
- ios - 应用程序被杀死时,如何每 10 秒将用户位置上传到服务器?
- javascript - Next.js:找不到模块:无法解析“canvg”
- angular - 如何使角度识别星云主题
- java - 无法打印传递给构造函数的数组
- fb-hydra - 递归 i 初始化以及如何在另一个配置组中使用配置组