Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will forgetting to call std::ofstream close function lead to memory leak?

I am just curious about the question: Will forgetting to call std::ofstream close function lead to memory leak? I give the following example to illustrate my question:

using namespace std;
ofstream myfile;
myfile.open ("C:\\report.html");
myfile << "<html lang=\"en\"> " << endl;
myfile << "<head>" << endl;

Normallly, we should also call myfile.close() at the end of the code script. However, if I forgot to call the close function, what would happen? Will it lead to memory leak? I have used memcheck and valgrind in linux to check the program, and no memory leak can be found. So what is the side effect if the close function is not called.

like image 900
feelfree Avatar asked Dec 15 '22 20:12

feelfree


1 Answers

When your std::ofstream object goes out of scope it will automatically be closed due to the use of RAII and the automatic calling of the object destructor.

In this situation your code is perfectly acceptable and would cause no memory leaks. There is no need to call close manually at all.

Only use close if you wish to reuse the object before it goes out of scope i.e if the ofstream object was a member of a class and you wish to re-use it then its possible to call close on it and then re-open it with a different file etc.

like image 145
const_ref Avatar answered Feb 06 '23 16:02

const_ref