mardi 23 août 2016

c++ std::ios_base::failure exception

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

The class failure defines 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 which emulates restricted resource environment while using of 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_alloc on stderr. One of online compilers shows the same output.

The question is: why exception type is std::bad_alloc and not std::ios_base::failure ?

Aucun commentaire:

Enregistrer un commentaire