开发者

Problematic vector return value - not really updated?

开发者 https://www.devze.com 2023-01-19 07:47 出处:网络
I\'m having this weird problem: when my program reach this method: //Returns the transpose matrix of this one

I'm having this weird problem: when my program reach this method:

//Returns the transpose matrix of this one
RegMatrix RegMatrix::transpose() const{
    RegMatrix result(numCol,numRow);
    int i,j;
    for(i=0;i<numRow;++i)
        for(j=0;j<numCol;++j){
            result._matrix[j][i] = _matrix[i][j];
        }

        return result;
}

it suddenly crashes...

When i ran it with my VS debugger, it looked just all fine, the new matrix was filled with the relevant values, till the line return result; that from some mysterious reason returned an empty matrix vector.

Where do i go wrong??


Here is my implementation for the copy constructor:

//CCtor of RegMatrix                    
RegMatrix::RegMatrix(const RegMatrix &other): numRow(other.getRow()), numCol(other.getCol()){

    //Create
    _matrix = vector<vector<MyDouble> >(other.getRow());
    int i,j;
    for(i=0; i < numRow; i++)
        _matrix[i] = vec开发者_StackOverflow中文版tor<MyDouble>(other.getCol());

    //Copy Matrix
    for(i=0;i<numRow; ++i){
        for(j=0;j<numCol; ++j){
            _matrix[i][j] = other._matrix[i][j];
        }
    }
}

My assignment operator implementation:

//RegMatrix = RegMatrix 
RegMatrix& RegMatrix::operator=(const RegMatrix rhs){
    assert(numRow == rhs.getRow() && numCol == rhs.getCol());
    if(*this != rhs){
        int i,j;
        for(i=0;i<numRow;++i)
            for(j=0;j<numCol;++j){
                _matrix[i][j] = rhs._matrix[i][j];
            }
    }

    return *this;
}


Assuming that MyDouble has a correct copy constructor, you should be able to reduce your copy constructor to just this:

RegMatrix::RegMatrix(const RegMatrix &other):numRow(other.getRow()), numCol(other.getCol()),
    _matrix(other._matrix)
{ }

See what that gets you.

Edit: Your assignment operator might be a problem if the columns and rows aren't equal. You're throwing an assert in that instance, so the program is going to abort. Is that what you want? Wouldn't you rather the assignment change the columns and rows to match the new values? If so, you can just do this:

RegMatrix & RegMatrix::operator=(const RegMatrix & rhs) {
    if(this == &rhs)
        return *this;
    numRow = rhs.getRow();
    numCol = rhs.getCol();
    _matrix = rhs._matrix;
    return *this;
}


You are returning the matrix by value. A copy constructor gets involved. How is your copy constructor defined?

0

精彩评论

暂无评论...
验证码 换一张
取 消