1
我運行了cppcheck,事實證明我需要爲此類創建一個複製構造函數。在這種情況下,我不知道如何定義一個拷貝構造函數。有什麼建議麼?如何定義複製構造函數並釋放指針
class Simulator{
private:
int xMax;// = 40; //SIZE;
int yMax;// = 40; //xMax; // 40
//int TTMxSize = 4000;
//const int CarMxSize = 500;
//const int WaitListSize = 4000;
double base_price;// = 0.85/4;
double saev_vott;// = 0.35;
char* mode_output;// = "modeChoiceStats_supply_charge.csv";
vector<Car>** CarMx;//[xMax][yMax];
vector <Station>** ChStMx;//[xMax][yMax];
vector<int> **cellChargeCount;
vector<int> **cellChargeTime;
int timeTripCounts [288];
// Functions for program
public:
Simulator();
Simulator(int fleet_size, int seed, char* inputFile);
~Simulator();
bool loadParameters(char* input);
void printParameters();
void placeInitCars();
bool lookForCar (int x, int y, int r, int dist, int& cn);
void assignCar (int x, int y, int c, Trip* trp);
void setBusinessTripProbability();
void runSimulation();
};
Simulator::~Simulator()
{
for (int x=0; x<xMax; x++)
{
delete [] CarMx[x];
delete [] ChStMx[x];
delete [] cellChargeCount[x];
delete [] cellChargeTime[x];
}
for (int x=0; x<numZonesL; x++)
delete [] zoneSharesL[x];
for (int x=0; x<numZonesS; x++)
delete [] zoneSharesS[x];
delete [] CarMx;
delete [] ChStMx;
delete [] cellChargeCount;
delete [] cellChargeTime;
delete [] zoneSharesL;
delete [] zoneSharesS;
}
而且,我得到資源泄漏的錯誤在以下功能
bool Simulator::loadParameters(char* input)
{
FILE* inputfile;
inputfile = fopen(input, "r");
if (inputfile == NULL){
cout << "Could not open "<<input<<endl;
return false;
}
double inputVal = -1.0;
char* varStr;
char* valStr;
char instring [80];
while (!feof(inputfile))
{
fgets(instring, 80, inputfile);
comment = instring[0];
if (comment != '#' && comment != '\n')
{
varStr = strtok(instring, "=");
valStr = strtok(NULL, "\0");
if (strcmp (varStr, "xMax") == 0) {
inputVal = strtod(valStr, NULL);
xMax = 4 * (int) inputVal;
} else if (strcmp (varStr, "yMax") == 0) {
inputVal = strtod(valStr, NULL);
yMax = 4 * (int) inputVal;
}
}
return true; <<<<<<<<< RESOURCE LEAK: inputfile
}
可能泄漏該功能:指針沒有被分配之前釋放。
void Simulator::setBusinessTripProbability()
{
businessTripProbability = new double[926];
businessTripProbability [ 0 ] = 0.0000 ;
businessTripProbability [ 1 ] = 0.0029 ;
businessTripProbability [ 2 ] = 0.0059 ;........... until [925]