在下面的代碼中,我遇到了問題。它表現爲bad_alloc異常,這是因爲傳遞給reader
的參數CompressedBufferReader
是一個錯誤的字符串。從構造函數調用構造函數
class FileReader {
FILE *file;
protected:
unsigned char *data; // local copy
long size;
public:
FileReader(const char *filename);
~FileReader();
unsigned long getSize();
unsigned char *getFileData();
};
class CompressedBufferReader {
unsigned char *buffer;
unsigned long len;
public:
CompressedBufferReader(unsigned char *);
~CompressedBufferReader();
unsigned char *getBuffer();
unsigned long getLength();
};
CompressedBufferReader::CompressedBufferReader(unsigned char *srcCompressed) {
len = 0; buffer = 0;
len = GetDecompressedBufferSize(srcCompressed);
buffer = new unsigned char[len]; if (!buffer) throw std::runtime_error("Cannot allocate!");
WriteDecompressedBuffer(buffer, len, srcCompressed);
}
CompressedBufferReader::~CompressedBufferReader() {
delete[] buffer;
}
unsigned char *CompressedBufferReader::getBuffer() {return buffer;}
unsigned long CompressedBufferReader::getLength() {return len;}
// similar interface to FileReader. Does not inherit because it does not benefit from doing so.
class CompressedFileReader {
CompressedBufferReader reader;
public:
CompressedFileReader(const char *filename);
unsigned char *getFileData();
unsigned long getSize();
};
CompressedFileReader::CompressedFileReader(const char *filename) : reader(FileReader(filename).getFileData()){} // this line is causing the problem
unsigned char *CompressedFileReader::getFileData() { return reader.getBuffer(); }
unsigned long CompressedFileReader::getSize() { return reader.getLength(); }
更具體地講,好像我創建匿名其數據內容可被傳遞到reader
構造變得之前釋放的的FileReader,一個CompressedBufferReader
。
的問題是,我不能寫CompressedFileReader
的構造函數的方式,讓我正確實例化一個FileReader
,因爲我打算用CompressedBufferReader
的構造,這意味着構造函數的身體之前,我必須調用它。一個catch-22的位。這個問題如何解決?
我覺得很難說沒有看到'FileReader'的實現是什麼問題。但是作爲一般性評論,您的代碼非常「手動」,如果您使用標準容器和字符串,讀取和維護可能會更加簡單。 –