我遇到指针和动态内存问题。我创建了一个类FileReader,它从一个像这样格式化的文件中读取。
名字,姓氏,年份,GPA
字符串,字符串,字符串,整数
克里斯,奈特,FR,3.8
米奇,泰勒,JR,3.5
第一行,我将其存储在一个名为Names
的向量中和向量中的第二行称为类型。
我还创建了一个包含void指针的向量,因为它将保存任意类型
我的问题是,如何释放堆中的内存?
#ifndef RECORD_H
#define RECORD_H
class Record{
private:
//POINTER VARIABLES
int *intPtr;
double *doublePtr;
vector<string*> stringPtrList;
//NAMES,TYPES, AND VALUES
vector<string> Names;
vector<string> Types;
vector<void*> Values;
public:
Record(vector<string> _names, vector<string> _types, vector<string>_values){
Names = _names;
Types = _types;
//ALOCATING MEMORY
for (unsigned i = 0; i < Types.size(); i++){
string *stringPtr = new string;
stringPtrList.push_back(stringPtr);
}
for (unsigned int i = 0; i < Types.size(); i++){
if (Types[i] == "Integer"){
intPtr = new int;
*intPtr = stoi(_values[i]);
Values.push_back((void*)intPtr);
}
else if (Types[i] == "Double"){
doublePtr = new double;
*doublePtr = stod(_values[i]);
Values.push_back((void*)doublePtr);
}
else if (Types[i] == "String"){
*stringPtrList[i] = _values[i];
Values.push_back((void*)stringPtrList[i]);
}
else{
cout << "No match Type" << endl;
}
}
}
Record(const Record &r){
int *intPtr = new int;
intPtr = r.intPtr;
double *doublePtr = new double;
doublePtr = r.doublePtr;
for (int i = 0; i < r.stringPtrList.size(); i++){
stringPtrList[i] = new string;
stringPtrList[i] = r.stringPtrList[i];
}
}
~Record(){
delete intPtr, doublePtr;
for (int i = 0; i < Types.size(); i++){
delete stringPtrList[i];
}
cout << "Pointer are deleted" << endl;
}
friend ostream&operator <<(ostream &os, const Record &r){
for (unsigned int i = 0; i < r.Types.size(); i++){
if (r.Types[i] == "Integer"){
os << "Integer: " << *(int*)r.Values[i] << endl;
}
else if (r.Types[i] == "String"){
os << "String" << *static_cast<string*>(r.Values[i]) << endl;
}
else if (r.Types[i] == "Double"){
os << "Double" << *(double*)r.Values[i] << endl;
}
else{
cout << "Fatal Error!" << endl;
}
}
cin.get();
return os;
}
};
#endif
答案 0 :(得分:0)
如果你真的必须能够处理任何类型,只需使用价值对类型的结构,类似于:
struct Record { 字符串值; VAR_TYPE类型; //这是你定义的一些枚举。 }
保留包含类型和列索引的列的列表,以便在阅读时轻松处理每个记录。 由于您知道每条记录的类型,因此您可以在实际使用时将其强制转换为该记录。
它更干净,不需要动态分配(这很慢)并且搞乱了void指针。