我有一个包含成员指针的类,该指针在其构造函数中动态分配,如下所示:
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
元素的指针的类,并且在同一指针上调用析构函数两次,但我不确定这是怎么发生的。我在这里做错了什么?
这是三规则的一个例子。如果你的类需要释放析构函数中的资源,它通常需要声明一个复制构造函数(和复制赋值运算符),以复制所拥有的资源、管理共享所有权或防止被复制。
Record getRecord(unsigned int numRecord) {return m_gdsRecords[numRecord];}
此函数返回Record
的副本。现在有两个包含相同m_bufRecord
指针的Record
。在这些Record
上运行析构函数将尝试删除同一指针值两次。