I have the following class:
class Patient {
public:
Patient(int x);
~Patient();
private:
int* RP;
};
Patient::Patient(int x) { RP = new int [x]; }
Patient::~Patient() { delete [] RP; }
I instantiate this class on the stack as follows:
void f() { Patient p(10); }
Now, when it returns f(), I get a “double release or damage” error, which signals me that something tried to delete more than once. But I do not understand why this is so. The space for the array is created on the heap, and only because the function from which the space was allocated from the inside is returned, I did not expect the space to be fixed.
I thought that if I allocated space on the heap (using the keyword new), then the only way to return this space is to use the delete keyword. Help!
, ( )
( .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;
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;
break;
default:
cerr << "Invalid biopsy result (" << result << ") at age " << age << "!\n";
}
}
void Patient::recordPSA(const int& age, const double& level) {
PSA[age-1] = level;
}
void Patient::recordPSA(const int& age) {
PSA[age-1] = -1;
}
, , . main() Policy, Patient:
void simulate1(Policy& P)
{
Patient patient(260);
for(int idx=0; idx<(P.size); idx++)
{
while(state != 9)
{
patient.recordPSA(age,PSA);
patient.recordPSA(age);
patient.recordBiopsy(age,biopsyResult);
patient.recordRP(age,true);
patient.recordRP(age,false);
}
}
}