Properly use RAII to reduce complication

This commit is contained in:
topjohnwu
2019-11-22 03:01:49 -05:00
parent 474cc7d56d
commit 5bee1c56a9
4 changed files with 48 additions and 83 deletions

View File

@@ -18,7 +18,6 @@ public:
virtual int read(void *buf, size_t len);
virtual int write(const void *buf, size_t len);
virtual off_t seek(off_t off, int whence);
virtual int close();
virtual ~stream() = default;
};
@@ -26,11 +25,10 @@ public:
class filter_stream : public stream {
public:
filter_stream(FILE *fp) : fp(fp) {}
~filter_stream() override { if (fp) close(); }
~filter_stream() override;
int read(void *buf, size_t len) override;
int write(const void *buf, size_t len) override;
int close() override;
void set_base(FILE *f);
template <class T, class... Args >

View File

@@ -19,9 +19,8 @@ static fpos_t strm_seek(void *v, fpos_t off, int whence) {
static int strm_close(void *v) {
auto strm = reinterpret_cast<stream *>(v);
int ret = strm->close();
delete strm;
return ret;
return 0;
}
FILE *open_stream(stream *strm) {
@@ -46,8 +45,8 @@ off_t stream::seek(off_t off, int whence) {
return -1;
}
int stream::close() {
return 0;
filter_stream::~filter_stream() {
if (fp) fclose(fp);
}
int filter_stream::read(void *buf, size_t len) {
@@ -58,12 +57,6 @@ int filter_stream::write(const void *buf, size_t len) {
return fwrite(buf, 1, len, fp);
}
int filter_stream::close() {
int ret = fclose(fp);
fp = nullptr;
return ret;
}
void filter_stream::set_base(FILE *f) {
if (fp) fclose(fp);
fp = f;