Question

I overwrote a + operator:

Matrix& Matrix::operator+(Matrix m1)
{
    //This should never be triggered
    if(this->data.capacity() != m1.data.capacity() || this->data[0].capacity() != m1.data[0].capacity())
    {
        cout << "Dimensions don't match, can't add.\n";
        throw 7;
    }
    vector<vector<double>> result;
    result.resize(m1.data.capacity());
    for(int i = 0; i < m1.data.size(); i++)
    {
        result[i].resize(m1.data[0].size());
        for(int j = 0; j < m1.data[0].size(); j++)
        {
            result[i][j] = m1.data[i][j] + this->data[i][j];
        }
    }
    return Matrix(m1.getRows(),m1.getCols(), result);
}

This is the corresponding Constructor:

Matrix::Matrix(int rows, int cols, vector<vector<double>> data)
{
    this->rows = rows;
    this->cols = cols;
    this->data = data;
}

Here's the executing code:

c = (a+b);

When I assign a breakpoint at the last line of the operator overload, I can see the correct results in result and both cols and rows are assigned correctly. When I step out, c has "rows" and "cols" set correctly, but data is empty. Why is that?

Was it helpful?

Solution

Your operator + is wrong. It should be returning a new object, not a reference to a local object (which is UB anyway).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top