gpt4 book ai didi

c++ - 为什么我不能使用 "delete"关键字回收动态分配的内存?

转载 作者:太空狗 更新时间:2023-10-29 19:59:54 26 4
gpt4 key购买 nike

我有以下类(class):

class Patient {
public:
Patient(int x);
~Patient();
private:
int* RP;
};

Patient::Patient(int x) { RP = new int [x]; }
Patient::~Patient() { delete [] RP; }

我在栈上创建了这个类的一个实例,如下所示:

void f() { Patient p(10); }

现在,当 f() 返回时,我收到“双重释放或损坏”错误,这向我发出信号,表明有人试图多次删除某些内容。但我不明白为什么会这样。数组的空间是在堆上创建的,仅仅因为分配空间的函数返回,我不希望空间被回收。

我认为如果我在堆上分配空间(使用 new 关键字),那么回收该空间的唯一方法是使用 delete 关键字。帮助!

根据要求,这是实际代码(为简洁起见略有删节)

这是完整的类定义(分为 .cpp.h 文件,但一起显示):

class Patient {

public:
Patient(int numDecisionEpochs);

~Patient();

void recordRP(const int& age, const bool& t);
void recordBiopsy(const int& age, const int& result);
void recordPSA(const int& age, const double& level);
void recordPSA(const int& age);
private:
int* RP;
int* Biopsy;
double* PSA;
};

Patient::Patient(int numDecisionEpochs) {
RP = new int [numDecisionEpochs];
Biopsy = new int [numDecisionEpochs];
PSA = new double [numDecisionEpochs];
}

Patient::~Patient() {
delete[] RP;
}

void Patient::recordRP(const int& age, const bool& t) {
if(t)
RP[age-1] = 1; // RP either yes (1) or no (0)
else
RP[age-1] = 0;
}

void Patient::recordBiopsy(const int& age, const int& result) {
switch(result)
{
case 0:
case 1:
case 2:
case 3:
case 4:
Biopsy[age-1]=result; // only permit results 0,1,2,3,4
break;
default:
cerr << "Invalid biopsy result (" << result << ") at age " << age << "!\n";
}
}

void Patient::recordPSA(const int& age, const double& level) {
PSA[age-1] = level; // record PSA volume
}

void Patient::recordPSA(const int& age) {
PSA[age-1] = -1; // symbol for no screening during epoch
}

接下来是使用上述类的函数。以下函数直接从 main() 调用,并传递了一个完全独立于 Patient 类的 Policy 对象:

void simulate1(Policy& P)
{
// ...
Patient patient(260);

for(int idx=0; idx<(P.size); idx++)
{
while(state != 9) // while patient not dead
{
// ...
patient.recordPSA(age,PSA);
// ...
patient.recordPSA(age);
// ...
patient.recordBiopsy(age,biopsyResult);
// ...
patient.recordRP(age,true);
// ...
patient.recordRP(age,false);
// ...

} // end patient (while loop)

} // end sample (for loop)

} // end function

最佳答案

您违反了 rule-of-three (或对于 C++11,rule-of-five )。您需要一个复制构造函数和复制赋值运算符来执行指针的深层复制。当然,由于您不跟踪所分配数组的大小,因此如果不引入第二个数据成员,这是不可能的。

关于c++ - 为什么我不能使用 "delete"关键字回收动态分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10097874/

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