简体   繁体   English

向量的错误内存分配C ++

[英]Bad memory allocation C++ for a vector

I get std_bad_alloc error in the following code. 我在以下代码中收到std_bad_alloc错误。 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. 当然,这意味着当发生类似A = B的赋值时,将生成B的副本并在函数的right参数处使用。 But in the current code that copy's only purpose would be to set the values of A and then be destroyed. 但是在当前代码中,复制的唯一目的是设置A的值,然后将其销毁。 You could just as well pass a const matrix& to avoid the copy. 您也可以传递const matrix&来避免复制。 (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 . 第二个问题是,这将返回一个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& 因此,您应该继续进行操作,然后将返回值键入matrix&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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