RAII Method for Receiving Errors Occurring during Failure

In a typical RAII example for input / output of files on Wikipedia, any errors that occur when closing a file are swallowed:

#include <iostream>
#include <string> 
#include <fstream>
#include <stdexcept>

void write_to_file (const std::string & message) {
    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed when leaving scope (regardless of exception)
}

There seems to be no way to determine if an error occurred while closing file; obviously, it is possible to call only file.rdstate(), but file- in the scope.

I could call file.close()manually and then check for an error, but I would have to do it in every place that I return from the scope, which defeats the RAII target.

, , , , , AFAIK , .

, RAII , ? , , .

, , - , , . , , ios_base::register_callback. , .

, , ?

, , , , try/catch .

+4
2

:

class Foo {
public:
    Foo() : count(std::uncaught_exceptions()) {}
    ~Foo() noexcept(false)
    {
        if (std::uncaught_exceptions() != count) {
            // ~Foo() called during stack unwinding
            // Cannot throw exception safely.
        } else {
            // ~Foo() called normally
            // Can throw exception
        }
    }
private:
    int count;
};
+4

, , ...

class MyFileHandler {
    std::ofstream& f_;
public:
    MyFileHandler(std::ofstream& f) : f_(f) {}
    ~MyFileHandler() {
        f_.close();
        // handle errors as required...
    }
    // copy and assignments elided for brevity, but should well be deleted
};

void write_to_file (const std::string & message) {
    // try to open file
    std::ofstream file("example.txt");
    MyFileHandler fileCloser(file);

    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed when leaving scope (regardless of exception)
}

std::ofstream .

+2

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


All Articles