【发布时间】:2021-09-19 20:21:36
【问题描述】:
我正在尝试在 C++ 中实现矩阵乘法。我找到了一个示例代码,它使用了一个写入.h 和.cpp 文件的类。这只是与我的问题相关的代码的一部分:
#include "Matrix.h"
// Constructor - using an initialisation list here
Matrix::Matrix(int rows, int cols, bool preallocate): rows(rows), cols(cols), size_of_values(rows * cols), preallocated(preallocate)
{
// If we want to handle memory ourselves
if (this->preallocated)
{
// Must remember to delete this in the destructor
this->values = new double[size_of_values];
}
}
void Matrix::matMatMult(Matrix& mat_left, Matrix& output)
{
// The output hasn't been preallocated, so we are going to do that
output.values = new double[this->rows * mat_left.cols];
// Set values to zero before hand
for (int i = 0; i < output.size_of_values; i++)
{
output.values[i] = 0;
}
我想知道为什么他们使用 0s output.values[i] = 0; 的输出矩阵来初始化它之前已经分配了内存?
【问题讨论】:
-
初始化可以更简单:
output.values = new double[this->rows * mat_left.cols]{}; -
"虽然之前已经分配了内存?" - 每次调用
matMatMult时都会进行新的分配。 -
这取决于算法应该做什么。如果你用 1:s 填充它,这个算法会做正确的事吗?
-
如果你不初始化它然后继续读取你的程序格式错误的任何索引处的值。它的行为是不确定的。
-
你不能通过实验可靠地检查未定义的行为,因为它可能看起来有效,它是未定义的
标签: c++ memory matrix-multiplication