does python have useless destructors?

David Turner dkturner at telkomsa.net
Mon Jun 14 03:35:14 EDT 2004


"Terry Reedy" <tjreedy at udel.edu> wrote in message news:<mailman.891.1087014838.6949.python-list at python.org>...
> "David Bolen" <db3l at fitlinxx.com> wrote in message
> news:u4qpi7yw0.fsf at fitlinxx.com...
> > Resource Acquisition is Initialization.
>  ,,,
> > It comes from a common method in C++ of using stack-allocated objects
> > to own or manage resources, because of the explicit construction and
> > destruction semantics of C++ objects (and their members) during
>  ...
> > I'm not sure if RAII is intended to also cover non-stack based
> > objects, in terms handing ownership of the object reference equating
> 
> Thanks.  This makes it much clearer what behavior some people miss, and why
> the behavior is hard to simulate in CPython (all PyObjects are heap
> allocated).
> 

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.  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.

Regards
David Turner



More information about the Python-list mailing list