When is stringbuf::flush called?
Asked Answered
P

1

1
struct encrypt_stream : public std::stringbuf
{
    int sync() { encrypt_buffer(); flush_to_device(); }
    ...
private:
    void encrypt_buffer();
    void flush_to_device();
};

I want to write this class to encrypt text data. Every time this stringbuf object is flushed, sync is called and an encrypted version of the buffer is sent to the device. The encrypted text strongly depends on the moment when flush is called. Are there tricky cases where flush can be called on this object without the user asking for it?

I know that flush is called when std::endl is received, but are there any other cases I am unaware of?

Prop answered 29/1, 2014 at 18:53 Comment(0)
H
5

flush() is called in these situations:

  • When std::endl is used (namely an explicit call to std::ostream::flush()) [§27.7.3.7/7]
  • When the stream's destructor is called [§27.5.3.1.6/4]
  • When the stream to which it is tie()-ed performs a read. [§27.7.2.1.3/2]
  • When the file stream is repositioned.
  • When the stream has reached the maximum allocated characters in its buffer, when overflow() is called to extract the content to the external device, [§27.6.3.4.5/3]
  • or in the case of input streams, when gptr() == egptr(), a call to underflow() to discard the content and synchronize its buffer with the external device. [§27.6.3.4.3/7]

This is what I know about the standard IOStreams. This could vary depending on the implementation of your stream or stream buffer.

Hopkins answered 29/1, 2014 at 18:57 Comment(2)
Good, but [citation needed]Procambium
@LightnessRacesinOrbit I'm on the hunt as we speak. :)Hopkins

© 2022 - 2024 — McMap. All rights reserved.