I have a small 10-liner function that writes some data to a file using an std::ofstream
. I did not explicitly call .close()
at the end of my function, but it failed code review with the reason that it is better to explicitly call it for style and verbosity reasons. I understand there is no harm in calling .close()
explicitly, but does calling it explicitly just before a return
statement indicate a lack of understanding or faith in RAII?
The C++ standard says:
§27.8.1.2
virtual ~ basic_filebuf ();
[3] Effects: Destroys an object of
class basic_filebuf<charT,traits>
. Callsclose()
.
Am I justified in my argument that calling .close()
at the end of a function is redundant and/or unnecessary?
bool SomeClass::saveData()
{
std::ofstream saveFile(m_filename);
if (!saveFile.is_open())
return false;
saveFile << m_member1 << std::endl;
saveFile << m_member2 << std::endl;
saveFile.close(); // passed review only with this line
return true;
}
The function is only supposed to return false
if the file could not be opened for writing.