错误的内存分配 C++对于一个向量

发布于 2024-09-26 21:07:18 字数 111 浏览 1 评论 0原文

我在以下代码中收到 std_bad_alloc 错误。问题似乎是当我将矩阵添加到向量中时,当我到达调试器中的该行时,程序崩溃了。问题是只有前两个矩阵从文件中读取,其他两个矩阵则没有,因为程序因上述错误而崩溃。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ま昔日黯然 2024-10-03 21:07:18

在复制构造函数中没有任何地方设置 numCols、numRows。

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

鹿童谣 2024-10-03 21:07:18

不是崩溃问题的答案(无论如何已经解决了),但应该注意的是,正如目前所写的那样,您的赋值运算符是不必要的浪费:

matrix matrix::operator =(const matrix right)

第一个问题是它按值获取参数。这当然意味着,当发生像 A = B 这样的赋值时,就会创建 B 的副本并在该函数的 right 参数中使用。功能。但在当前代码中,复制的唯一目的是设置 A 的值,然后被销毁。您也可以传递一个 const matrix& 来避免复制。 (或者,您可以将参数保留为按值副本,但将整个运算符实现为 复制和交换。)

第二个问题是它返回一个矩阵。这还可能导致创建不必要的临时副本。即使编译器可能能够优化副本,但返回值根本没有意义。赋值运算符的标准形式返回对被赋值对象的引用。因此,您应该继续将返回类型设置为 matrix&

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&

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文