gpt4 book ai didi

c++ - 析构函数导致程序崩溃

转载 作者:行者123 更新时间:2023-11-28 02:36:33 24 4
gpt4 key购买 nike

我真的很难理解将析构函数与复制构造函数一起使用的概念。如果我不使用析构函数,代码可以正常工作,因为它会自动执行。如果我这样做,我会收到一条错误消息“调试断言失败!”和表达式:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)。

但我希望能够理解如何使用析构函数。这是下面的代码,非常感谢帮助解释我做错了什么或需要做什么!
类矩阵 {

private:
int M;
int N;
double *data;

public:
Matrix();
int getM() const { return M; }
int getN() const { return N; }

//CONSTRUCTOR
Matrix(int sizeR, int sizeC,double * input_data)
{
M = sizeR; //Rows
N = sizeC; //Columns

data = new double[M*N]; //creation of 1D array, uses m&n values

cout << "\nMatrix::Matrix(int sizeR, int sizeC, double * data_value) is invoked...\n\n";

//ENTER DATA INTO MATRIX HERE:
for(int i=0; i < M*N; i++) //Loops for every data entry into 1D array, uses r&c as referenece to
data[i] = input_data[i];//Accesses each value at specific location, inputs value 'val'
for(int i = 0; i < M*N; i++) //Loops for every data entry into 1D array, uses r&c as referenece to size
cout << data[i] << " ";
}

//get function uses row and column from user
double get(int i, int j)
{
return data[i*N+j];
}

double set(int i, int j, double val)
{
data[i*N+j] = val;

cout << "\n\nNEW MATRIX: ";
for(int i = 0; i < M*N; i++)//Loops for every data entry into 1D array, uses r&c as referenece to size
cout << data[i] << " ";

return val;
}

Matrix(const Matrix& oldMatrix)
{
cout¸<< "\nMatrix::Matrix(const Matrix&) is invoked....";
M = oldMatrix.getM();
N = oldMatrix.getN();
data = oldMatrix.data;

cout << "\n\n";

//ENTER DATA INTO MATRIX HERE:

for(int i = 0; i < M*N; i++)//Loops for every data entry into 1D array, uses r&c as referenece to size
cout << data[i] << " ";

}

//DESTRUCTOR
~Matrix()
{
//delete data
delete [] data;
data = NULL;
cout << "\n\nMatrix::~Matrix() is invoked...\n\n";
}



};

int main()
{
int sizeR, sizeC;
double val;

cout << "Enter No. Rows: ";
cin >> sizeR;

cout << "Enter No. Columns: ";
cin >> sizeC;

double * input_data;


input_data = new double[sizeR*sizeC];

//INPUTS VALUES TO ARRAY
for(int i = 0; i < sizeR*sizeC; i++)//Loops for every row
input_data[i] = i;

Matrix M1(sizeR, sizeC, input_data);

cout << "Enter row that value you are after is in: ";
cin >> sizeR;
cout << " & now the column that it is in: ";
cin >> sizeC;


cout << "Change value: " << M1.get(sizeR, sizeC) << " to:";
cin >> val;
M1.set(sizeR, sizeC, val);

//calls copy constructor
M1 = Matrix(M1);
}

最佳答案

在复制构造函数中,您复制指针,这意味着您现在拥有两个具有相同指针的对象。如果其中一个对象被破坏,则它会为另一个对象留下一个现在无效的指针。

以任何方式取消引用此指针,或尝试释放它,将导致 undefined behavior .

有问题的行是这一行:

M1 = Matrix(M1);

该行创建了一个临时对象,并将M1中的数据复制到该临时对象中,然后将临时对象分配回M1 (并且编译器生成的复制赋值运算符只会对成员进行浅拷贝,因此与您的复制构造函数没有太大区别)然后破坏临时对象,导致 M1 中的杂散和无效指针


在一个稍微相关的问题上,您可能还想了解 the rule of three .

关于c++ - 析构函数导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27230890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com