我有一个包含成员指针的类,该指针在其构造函数中动态分配,如下所示:
class Record {
public:
Record(unsigned short numBytes, char* bufRecord);
~Record();
unsigned short size() {return m_numBytes;}
private:
unsigned short m_numBytes;
char* m_bufRecord;
};
Record::Record(unsigned short numBytes, char* bufRecord) {
m_numBytes = numBytes;
m_bufRecord = new char[numBytes];
for(unsigned short i=0; i<numBytes; i++)
m_bufRecord[i] = bufRecord[i];
}
Record::~Record() {
delete m_bufRecord;
}
它基本上将输入缓冲区复制到动态分配的成员缓冲区中。我继续在另一个类的构造函数中使用这个类:
class File {
public:
File(const char* fileName);
~File();
unsigned int numRecords() {return m_records.size();}
Record getRecord(unsigned int numRecord) {return m_gdsRecords[numRecord];}
private:
std::ifstream m_file;
std::vector<Record> m_records;
};
File::File(const char* fileName) : m_file(fileName, ios::in | ios::binary) {
while(!m_file.eof()) {
char bufNumBytes[2];
char* bufRecord;
unsigned short numBytes;
m_file.read(bufNumBytes, 2);
numBytes = (bufNumBytes[0] << 8) + bufNumBytes[1] - 2;
bufRecord = new char[numBytes];
m_file.read(bufRecord, numBytes);
Record record(numBytes, bufRecord);
m_records.push_back(record);
delete bufRecord;
}
}
但是,当我实例化此类时,出现以下错误,这似乎表明我正在双重释放m_bufRecord
:
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000001cb3280 ***
我猜问题在于插入了一个包含指向vector
元素的指针的类,并且在同一个指针上调用了两次析构函数,但我不确定这是怎么发生的。我在这里做错了什么?