...
Note that std::basic_ifstream<T>
, std::basic_ofstream<T>
, and std::basic_fstream<T>
all maintain an internal reference to a std::basic_filebuf<T>
object on which open()
and close()
are called as-needed. Properly managing an object of one of these types (by not leaking the object) is sufficient to ensure compliance with this rule. Oftentimes, the best solution is to use the stream object by value semantics instead of via dynamic memory allocation, ensuring compliance with MEM31MEM51-CPP. Properly deallocate dynamically allocated resources. However, that is still insufficient for situations where destructors are not automatically called.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <exception>
#include <fstream>
#include <string>
void f(const std::string &N) {
std::fstream f(N);
if (!f.is_open()) {
// Handle error
return;
}
// ...
std::terminate();
} |
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <exception>
#include <fstream>
#include <string>
void f(const std::string &N) {
std::fstream f(N);
if (!f.is_open()) {
// Handle error
return;
}
// ...
f.close();
if (f.fail()) {
// Handle error
}
std::terminate();
}
|
...
Related Guidelines
CERT C++ Coding Standard | MEM31MEM51-CPP. Properly deallocate dynamically allocated resources |
CERT C Coding Standard | FIO42-C. Close files when they are no longer needed |
...