4 ms·
#include <fstream> using namespace std; int main() { { fstream f( "test.txt", ios::out ); f << "Hello" << endl; } // File gets closed
by wedesoft 17y ago
#include <fstream>
using namespace std;
int main()
{
{
fstream f( "test.txt", ios::out );
f << "Hello" << endl;
} // File gets closed
// ...
return 0;
}
- weaksauce 17y agoI haven't done C++ in a while but is it possible to allocate an fstream object on the heap instead of the stack? If so and you do not explicitly call delete on it then will it still close the file when going out of scope? Something like: #include <fstream> using namespace std; int main() { { fstream *f = new fstream( "test.txt", ios::out ); f << "Hello" << endl; } // memory leak and non closed file. // ... return 0; }
- scott_s 17y agoYou can allocate an fstream (or any) object on the heap, and if you do not explicitly call delete it will not close the file. Resource-acquisition-is-object-instantiation (RAIOI) is a common C++ idiom, and it only works on stack variables.
- altano 17y agoIt only works with stack variables, but you can wrap the construction and destruction of anything, including heap-allocated objects, with a stack variable. You tie the allocation of the heap object to the constructor of the stack variable, and the reverse for de-allocation/destructor. The premise of all this is that the construction and destruction of stack variables both happen at well known times and are guaranteed to occur.
- wedesoft 17y agoNo. But you can put a smart pointer object on the stack. #include <boost/smart_ptr.hpp> #include <fstream> using namespace boost; using namespace std; int main() { { shared_ptr< fstream > f( new fstream( "test.txt", ios::out ) ); *f << "Hello" << endl; } // File gets closed // ... return 0; }
- deleted 17y ago[deleted]