我想为矩阵及其运算制作一个矩阵库,但它有内存问题,然后我决定制作运算符 ovarloading 以避免内存泄漏。 = 运算符重载不起作用
matrix<double> k = func(b);
或
k = func(b);
当我在 for 循环中时
还有
matrix& operator=(const matrix& other)
和 matrix<T> operator=(const matrix<T>& other)
之间有什么区别?
这里是仅求和运算符的完整代码。 (我已声明 bool real 来决定它是 a + b + c 等操作的输出以及临时还是永久)
#include <iostream>
template <typename T>
class matrix{
public:
T *data;
int col;
int row;
int size;
bool real;
matrix(int col , int row){// declare matrix<T> r(40,40);
this->data = new T[col * row];
this->col = col;
this->row = row;
this->size = col * row;
real = true;
}
matrix(){ // declare matrix<T> r;
this->data = nullptr;
this->col = -1;
this->row = -1;
this->size = -1;
}
void print(){
for(int i=0; i<this->col; i++){
for(int j=0; j<this->row; j++)
std::cout << *(this->data + this->row * i + j ) << " "; //note format is decided to *(data + i) cuz other format is confussing for me whenever 2d matrix. sry
std::cout << std::endl;
}
}
void operator=(const T& num){// fill
for(int i=0; i<this->size; i++)
*(this->data + i) = (T)num;
}
void operator=(matrix<T> other){ // mix
if(other.real){ // copy
col = other.col;
row = other.row;
size = other.size;
data = new T[size];
for(int i=0; i<size; i++)
*(data + i) = *(other.data + i);
}
else{ //replace
delete data;
col = other.col;
row = other.row;
size = other.size;
data = other.data;
}
}
// SUM
matrix<T> operator+(const matrix<T>& other){
if(this->real == 1 && other.real == 1){
matrix<T> r(this->col, this->row);
for(int i=0; i<this->size; i++)
*(r.data + i) = *(this->data + i) + *(other.data + i);
r.real = false;
return r;
}
else if(this->real == 1 && other.real == 0){
matrix<T> r = other;
for(int i=0; i<this->size; i++)
*(r.data + i) += *(this->data + i);
r.real = false;
return r;
}
else if(this->real == 0 && other.real == 1){
matrix<T> *r = this;
for(int i=0; i<this->size; i++)
*(r->data + i) += *(this->data + i);
r->real = false;
return *r;
}
else{
matrix<T> *r = this;
for(int i=0; i<this->size; i++)
*(r->data + i) += *(this->data + i);
r->real = false;
delete other.data;
return *r;
}
}
};
template <typename T>
matrix<T> func(matrix<T> a){
matrix<T> r = a;
r.real = false; // while its false, gives error. also while its true, gives memory leak
r = 3;
return r;
}
int main(){
matrix<double> b(20,20);
b = 2;
matrix<double> k;
// for(int i=0; i<1000000; i++)
for(int i=0; i<10; i++)
k = func(b);
k.print();
return 0;
}
注意:我不想使用向量
注意:我将使用这个矩阵库进行神经网络
让我们从使用矩阵的示例开始
k = func(b);
template <typename T>
matrix<T> func(matrix<T> a) // 0
{
matrix<T> r = a; // 1
r.real = false;
r = 3; // 2
return r; // 3
} //4
b
到 a
,通过声明矩阵是按值获取的。现在你有两个矩阵,a
是一个本地对象。由
operator=(matrix<T>)
完成,因为没有
matrix::matrix(const Matrix&)
,它确实创建自己的副本,按值获取矩阵。退出该运算符后,由于没有析构函数,您会遇到泄漏;
matrix::matrix(const Matrix&)
的工作,但是使用
operator=(matrix<T>)
时,另一个矩阵泄漏;使用了
operator=
内制作了另一个副本,另一个泄漏!
a
分配的内存被泄漏,如果
r
为 true,则
real
被泄漏。