does python have useless destructors?

Aahz aahz at pythoncraft.com
Mon Jun 14 17:25:12 EDT 2004


In article <e251b7ba.0406132335.6e65beba at posting.google.com>,
David Turner <dkturner at telkomsa.net> wrote:
>
>In fact, the RAII idiom is quite commonly used with heap-allocated
>objects.  All that is required is a clear trail of ownership, which is
>generally not that difficult to achieve.  

Not really.  What you're doing is what I'd call "virtual stack" by
virtue of the fact that the heap objects are being managed by stack
objects.

>Here's some C++ code I wrote recently:
>
>typedef boost::shared_ptr<std::ifstream> file_ptr;
>typedef std::stack<file_ptr> file_stack;
>
>file_stack files;
>
>files.push(file_ptr(new std::ifstream(file_to_compile)));
>while(!files.empty())
>{
>    std::ifstream& f = files.top().get();
>    token << f;
>    if (token == Token::eof)
>        files.pop();
>    else
>        parse(token);
>}
>
>The RAII object in this case is std::ifstream.  What I have is a stack
>of file objects, wrapped in the reference-counting container
>boost::shared_ptr.  I know that the files will be closed no matter
>what happens in the while() loop, because the ifstream class closes
>the file when it is destroyed.  It will be destroyed by shared_ptr
>when the last reference disappears.  The last reference will disappear
>(assuming stored another reference in some outer scope) when the
>"files" container goes out of scope.
>
>It's pretty darn hard to mess something like this up.  So yes, you
>*can* use heap-based objects as RAII containers.

It's pretty darn easy: what happens when you pass those pointers outside
of their stack holders?  That's a *normal* part of Python programming;
changing that requires a whole new paradigm.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha



More information about the Python-list mailing list