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. 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
bgColor#FFcccc
langcpp
#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
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 Guidelines

...