-1

我有一个包含成员指针的类,该指针在其构造函数中动态分配,如下所示:

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元素的指针的类,并且在同一个指针上调用了两次析构函数,但我不确定这是怎么发生的。我在这里做错了什么?

4

2 回答 2

1

这是三法则的一个例子。如果您的类需要在析构函数中释放资源,它通常需要声明一个复制构造函数(和复制赋值运算符),以复制拥有的资源、管理共享所有权或防止被复制。

于 2013-02-10T17:35:36.930 回答
0
Record getRecord(unsigned int numRecord) {return m_gdsRecords[numRecord];}

此函数返回Record. 所以现在你有两个Records 包含相同的m_bufRecord指针。在这些Records 上运行析构函数将尝试删除相同的指针值两次。

于 2013-02-10T17:26:29.967 回答