Home > OS >  Is it valid to pass use nullptr as a streambuf, to default initialize std::istream?
Is it valid to pass use nullptr as a streambuf, to default initialize std::istream?

Time:11-11

Is this code standard-compliant?

class MyIstream : std::istream {
    MyStreamBuf buf;
public:
    MyIstream():
        std::istream(nullptr)
    {
        set_rdbuf(&buf);
    }
}

Do I have to create MyDummyStreamBuf, to bypass lack of default istream c-tor?

CodePudding user response:

https://en.cppreference.com/w/cpp/io/basic_ios/rdbuf

says

  1. Returns the associated stream buffer. If there is no associated stream buffer, returns a null pointer.

Seems to me like it is valid to have an istream (basic_istream/basic_ios) with no stream associated, iow with nullptr.

BTW, I would perhaps use rdbuf(...), instead of set_rdbuf(). Interestingly, rdbuf(ptr) also seems to explicitly allow passing a nullptr:

  1. Sets the associated stream buffer to sb. The error state is cleared by calling clear(). Returns the associated stream buffer before the operation. If there is no associated stream buffer, returns a null pointer.
  •  Tags:  
  • c
  • Related