On 3 Aug, 04:03, sturlamolden <sturlamol...@yahoo.no> wrote: > struct File { > std::FILE *fid; > File(const char *name) { > // acquire resource in constructor > fid = std::fopen(name); > if (!fid) throw some_exception; > } > ~File() { > // free resource in destructor > if(fid) std::flose(fid); > } > > };
And since this is comp.lang.python, I'll add in that this sometimes applies to Python as well. Python, like C++, can have the call stack rewinded by an exception. If we call some raw OS resource allocation, e.g. malloc or fopen using ctypes, we have to place a deallocation in __del__ (and make sure the object is newer put in a reference cycle). The safer option, however, is to use a C extension object, which is guaranteed to have the destructor called (that is, __dealloc__ when using Cython or Pyrex). If we place raw resource allocation arbitrarily in Python code, it is just as bad as in C++. But in Python, programmers avoid this trap by mostly never allocating raw OS resources from within Python code. E.g. Python's file object is programmed to close itself on garbage collection, unlike a pointer retured from fopen using ctypes. Sturla -- http://mail.python.org/mailman/listinfo/python-list