0

I am writing a std::istream subclass, which uses its own std::stringbuf subclass

class decostream : public std::istream
{
public:
    decostream(std::istream * input)
        : std::istream(new decostreambuf(input))
        {
        }

    ~decostream() { delete rdbuf(); }
}

Is this valid? From std::istream documentation it is difficult to know if the streambuf must be still valid when the istream is destroyed.

galinette
  • 8,896
  • 2
  • 36
  • 87
  • Valid? Yes. Dodgy? Hell yes. Make the buf a member of `decostream` instead. If anything removes or changes the associated buffer you'll leak the buffer (bad enough), and potentially delete a buffer that you don't own / wasn't heap allocated (fatal). All this assumes that `decostringstream` derives from `streambuf`, why the confusing name? – user657267 Oct 15 '14 at 07:10
  • I think @user657267 is right. At least this is what is suggested [here](http://stdcxx.apache.org/doc/stdlibug/39-3.html), coming from this answer http://stackoverflow.com/a/6490625/1133179. – luk32 Oct 15 '14 at 07:28
  • Sorry for the confusing name, this was a mistake when writing the simplified example. Fixed now. – galinette Oct 15 '14 at 09:30
  • If I make the decostreambuf as a member variable of decostream, it will be constructed AFTER I pass it to istream constructor, so this is quite bad. I cannot pass a null pointer to istream constructor and set the streambuf afterwards in the constructor body : I must pass a valid streambuf pointer. – galinette Oct 15 '14 at 09:34

1 Answers1

0
#include <istream>
#include <sstream>

class decostreambuf : public std::stringbuf {
public:
    decostreambuf(std::istream* input) {
        //...
    }
};

class decostream : public std::istream {
public:
    decostream(std::istream* input) : sb(input), std::istream(&sb) {
        //...
    }
private:
    decostreambuf sb;
};
StandBone
  • 9
  • 4