Question

I get std_bad_alloc error in the following code. It seems the problems is when I add the matrix to the vector, the program crashes when I get to that line in the debugger. The problem is that only the first two matrices are read from the file, the other two aren't because the program crashes with the above error.

Was it helpful?

Solution

Nowhere in your copy constructor do you set numCols, numRows.

OTHER TIPS

Not the answer to the crash problem (which has been taken care of already anyway), but it should be noted that your assignment operator is needlessly wasteful as currently written:

matrix matrix::operator =(const matrix right)

The first issue is that it is taking the parameter by value. This of course means that when an assignment like A = B occurs, then a copy of B is made and used at the right parameter of the function. But in the current code that copy's only purpose would be to set the values of A and then be destroyed. You could just as well pass a const matrix& to avoid the copy. (Alternatively, you could leave the parameter as a by-value copy but implement whole operator as a copy-and-swap.)

The second issue is that this is returning a matrix. This could also result in a needless temporary copy being created. And even though the compiler might be able to optimize away the copy, there's no purpose for the return to be a by-value copy at all. The standard form of an assignment operator returns a reference to the object that was assigned to. So you should just go ahead and make that return type a matrix&

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