开发者

Bad memory allocation C++ for a vector

I get std_bad_alloc error in the following code. It seems the problems is when I add the matrix to the vect开发者_运维技巧or, 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.


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


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&

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜