简体   繁体   中英

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 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.

在副本构造函数的任何地方都没有设置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&

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM