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

Den*_*ger 0 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);
}
Run Code Online (Sandbox Code Playgroud)

这是相应的构造函数:

Matrix::Matrix(int rows, int cols, vector<vector<double>> data)
{
    this->rows = rows;
    this->cols = cols;
    this->data = data;
}
Run Code Online (Sandbox Code Playgroud)

这是执行代码:

c = (a+b);

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

Pau*_*zie 5

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