首页 > 解决方案 > 重载包含 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 之前,析构函数就被调用了。我希望第二个代码在析构函数也能正常工作的情况下正常工作。我在这里做错了什么???

标签: c++operator-overloadingdestructor

解决方案


推荐阅读