3 ms·
Sure and I understand all that. My comment was just that the examples in the article are perhaps not the best ones to use because they are simply replicating w
by kscaldef 17y ago
Sure and I understand all that. My comment was just that the examples in the article are perhaps not the best ones to use because they are simply replicating what other languages do with lexically scoped variables, and users of those languages view the lack of such as a deficiency of Ruby.
- swannodette 17y agoHow does a lexically scoped variable close the file? I couldn't find any documentation about this while Google searching. Is this a real language feature where you can specify what happens to a variable when it goes out of scope? In other words, is it a baked-in convenience or a real extensible abstraction?
- kscaldef 17y agoYes, you can absolutely specify a destructor which will be called when a lexical / local variable goes out of scope in Perl or C++ (just to name the most well-known languages with this feature).
- 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]