我有一个名为 Matrix 的类,带有二维指针 bool** 矩阵。
看看这段代码:
void Matrix::operator=(const Matrix& A){
cout << "address in A : " << A.matrix << endl ;
cout << "address in y : " << matrix << endl ;
//return *this;
}
我在我的主函数中调用了我的 = 运算符,如下所示:
Matrix x(3,5);
Matrix y(3,5);
x.set(1,4,1);
cout << "address out X: " << x.matrix << endl;
cout << "address out Y: " << y.matrix << endl;
y = x;
cout << "address out X: " << x.matrix << endl;
cout << "address out Y: " << y.matrix << endl;
析构函数是这样的:
Matrix::~Matrix(){
cout << "address de : " << matrix <<endl;
for (int i=0;i<m;i++)
delete[] matrix[i];
delete[] matrix;
cout << "address de finish : " << matrix <<endl;
}
当我在 xcode 中运行我的程序时,我得到:
address out X: 0x100103ab0
address out Y: 0x100103af0
address in A : 0x100103ab0
address in y : 0x100103af0
address out X: 0x100103ab0
address out Y: 0x100103af0
address de : 0x100103af0
address de finish : 0x100103af0
address de : 0x100103ab0
address de finish : 0x100103ab0
它看起来不错,但是当我像这样更改 = 运算符函数时:
Matrix Matrix::operator=(const Matrix& A){
cout << "address in A : " << A.matrix << endl ;
cout << "address in y : " << matrix << endl ;
return *this;
}
我得到这个结果:
address out X: 0x100103ab0
address out Y: 0x100103af0
address in A : 0x100103ab0
address in y : 0x100103af0
address de : 0x100103af0
address de finish : 0x100103af0
address out X: 0x100103ab0
address out Y: 0x100103af0
address de : 0x100103af0
Thesis(26190) malloc: *** error for object 0x100103b10: pointer being freed was not allocated
谁能向我解释为什么析构函数在后一个代码中触发得更快?!我该如何预防
先感谢您