在c ++中使用析构函数来删除指针

时间:2013-06-28 10:19:17

标签: visual-c++ destructor

我有以下内容:

//in Matrix.h
class Matrix
{
public:
    Matrix (int _row1=1, int  _col1=1);
    Matrix(const Matrix &);
    ~Matrix();

    int row1;
    //int row2;
    int col1;
    double **m;
    //other functions and members...
    void Print(int id);

}

//In Matrix.cpp
Matrix::Matrix(int _row1, int  _col1): row1(_row1),col1(_col1)
{
    m=(double **) new double[row1];
    for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];
    for(long p=0;p<row1;p++) for (long q=0;q<col1;q++) m[p][q]=0.0;
}


//copy constructor
Matrix::Matrix(const Matrix &Mat){

    m=(double **) new double[row1];
    **m=**Mat.m;// copy the value
}
// Destructor
Matrix::~Matrix(void){
     //We need to deallocate our buffer
    delete[] *m;
    delete [] m;
     //Set m to null just in case
    m=0;
    cout<<" Freeing m "<<endl;
}
void Matrix::Print(int id)
{
cout<<"Element ID: "<<id<<endl;
for(int i=0; i<row1; i++) {
    for(int j=0;j<col1;j++) {
        cout<<m[i][j];
        if(j==col1-1) cout<<"\n";
    }
}
system("PAUSE");
}

如下调用:

elem[e].d0 = matel[i].OrgD;// Both Matrix
elem[e].d0.Print(1); // checking to see if at all copied

失败了:

void Matrix::Print(int id){
//...
 cout<<m[i][j];//here
...//
}

事实上,在其他函数使用m [i] [j]的地方它失败了。 只有连续使用任何对象时才会发生这种情况。如果我发表评论,这个错误就会消失 淘汰了。我不明白?任何帮助!

编辑1:我已将复制构造函数更改为:

Matrix::Matrix(const Matrix &Mat):row1(Mat.row1),col1(Mat.col1)
{
 m= new double *[row1];
 for(long p=0;p<row1;p++) m[p]=new double [col1];
 for(long p=0;p<row1;p++)for (long q=0;q<col1;q++) m[p][q]=Mat.m[p][q];
    // copy   the Value
}

并将赋值运算符设为:

Matrix& Matrix::operator = (const Matrix& o) {
  if ( this == &o ) {
    return *this; //Self assignment : nothing to do
}

delete[] *m;
delete[] m;

row1 = o.row1;
col1 = o.col1;
m = new double*[row1];
for(long p=0;p<row1;p++) m[p]=new double [col1];

for(long p=0;p<row1;p++) for (long q=0;q<col1;q++) m[p][q]=o.m[p][q];

return *this;
}

现在它失败了:

Matrix::Operator=...
  {
    o.m[p]  0xcdcdcdcd  double *
    CXX0030: Error: expression cannot be evaluated  // in the debugger

  }

我注意到,如果存在析构函数删除'm',那么使用'.m'的所有函数都会发生相同的事情,即调用对象的m不可用。希望得到一些答案。

1 个答案:

答案 0 :(得分:0)

在您使用的构造函数中

m=(double **) new double[row1];
for(long p=0;p<row1;p++) m[p]=(double *) new double[col1];

new double[row1]的类型为double[]。你把它投射到double**。如果你真的想得到一个双指针数组,你应该在这里使用new (double*)[row1]

相关问题