Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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. OftentimesOften, the best solution is to use the stream object by value semantics instead of via dynamic memory allocation, ensuring compliance with MEM51-CPP. Properly deallocate dynamically allocated resources. However, that is still insufficient for situations where in which destructors are not automatically called.

...

In this noncompliant code example, a std::fstream object f is constructed. The constructor for std::fstream calls std::basic_filebuf<T>::open(), and the default std::terminate_handler called by std::terminate() is std::abort(), which does not call destructors. ThusConsequently, the underlying std::basic_filebuf<T> object maintained by the object is not properly closed, and the program has no way of determining if whether an error occurs while flushing or closing the file.

...

In this compliant solution, std::fstream::close() is called prior to calling before std::terminate() is called, ensuring that the file resources are properly closed.:

Code Block
bgColor#ccccff
langcpp
#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 Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

[ISO/IEC 14882-2014]27.9.1, "File Streams"

 

...