矢量值不能永久保存[C ++ Rookie]

时间:2014-02-21 17:20:27

标签: c++ memory-management operator-keyword

我覆盖了一个+运算符:

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

这是相应的构造函数:

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

这是执行代码:

c = (a+b);

当我在操作符重载的最后一行分配断点时,我可以在result中看到正确的结果,并且正确分配了cols和rows。当我走出去时,c已正确设置“行”和“列”,但数据为空。那是为什么?

1 个答案:

答案 0 :(得分:5)

您的运营商+错了。它应该返回一个新对象,而不是对本地对象的引用(无论如何都是UB)。