What is the maximum size of std::ostringstream buffer?

后端 未结 2 1103
终归单人心
终归单人心 2021-01-21 06:45

Is the size allotted based on amount of dynamically allotted memory available? what happens when we reach this limit is there an exception thrown or it overwrites to some other

相关标签:
2条回答
  • 2021-01-21 07:32

    The buffer of a std::stringstream object is a wrapper around a std::string object. As such, the maximum size is std::string::max_size(). When the stream cannot allocate further, an exception will be thrown by the buffer which is probagated to the stream. The response is to turn on std::ios_base::badit in its stream state. Attempting to write pass this point will do nothing unless the stream state is cleared and the buffer is at least partially emptied.

    0 讨论(0)
  • 2021-01-21 07:37

    Just like std::cout, if the stream fails (for whatever reason), the state of the buffer will be set (eofbit, failbit, or badbit). This will mean that operator bool() for the stream will evaluate to false.

    std::ostringstream oss;
    // a lot of output to oss here - causing a situation where you are out of available memory
    if (!(oss << some_value))
    {
        // oss failed to write some_value!
    }
    

    Note: Prior to C++11, this was done via operator void*().

    Also, If you wanted the stream to throw an exception (it won't by default), you can register it to throw using the std::ios::exceptions() function.

    0 讨论(0)
提交回复
热议问题