C ++ std :: ios_base :: exception error

Standard ( N3337) says ( 27.5.3.1.1 Class ios_base::failure):

A class error determines the base class for the types of all objects thrown as exceptions by functions in the iostreams library, to report errors detected during stream buffer operations.

I have a simple test program that emulates a limited resource environment when using std :: ostringstream:

#include <sys/time.h>
#include <sys/resource.h>

#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include <iostream>
#include <sstream>

int main(int argc, const char* argv[])
{
    rlimit limit;
    limit.rlim_cur = limit.rlim_max = 268435456;

    if(setrlimit(RLIMIT_AS, &limit)) {
        std::cerr << "Cannot set resource limit: " << strerror(errno) << std::endl;
        exit(EXIT_FAILURE);
    }

    std::ostringstream os;
    os.exceptions(std::ostringstream::badbit);

    try {
        auto iterations = 1024 * 1024 * 1024;

        while(iterations && --iterations) os << 'F';

    } catch(const std::ios_base::failure& ex) {
        std::cerr << "Caught: std::ios_base::failure" << std::endl;
    } catch(const std::bad_alloc& ex) {
        std::cerr << "Caught: std::bad_alloc" << std::endl;
    } catch(...) {
        std::cerr << "Caught: ellipsis" << std::endl;
    }

    return 0;
}

In my environment (Linux, gcc 5.3.0) I got Caught: std::bad_allocon stderr. One of the online compilers shows the same result.

The question arises: why the type of exception std::bad_alloc, and not std::ios_base::failure?

+4
source share
2

os << 'F'; operator<<(ostream&, char), , 27.7.3.6.1 [ostream.formatted.reqmts],

. , setstate(ios_base::failbit), . , ios::badbit , ios::failure. *this s. (exceptions()&badbit) != 0,

stringbuf::overflow, 27.8.2.4[stringbuf.virtuals]p8, . libstd++ lib++ :

libstd++, std::bad_alloc stringbuf::overflow, operator<< (, __ostream_insert), __ostream_insert , , .

lib++, std::bad_alloc stringbuf::overflow, overflow return traits::eof, , , ( , steambuf::xsputn) , turn, , __pad_and_output, rdbuf, , , __put_character_sequence, badbit, failbit. badbit ios::failure.

, lib++ stringbuf::overflow:

'' : '' traits::eof() .

, , , , libstd++ . ( libstd++ stringbuf::overflow eof, string::max_size bad_alloc)

+2

, . - , bad_alloc. , .

bad_alloc ios_base:: debatable, . , bad_alloc.

0

Source: https://habr.com/ru/post/1652189/


All Articles