does python have useless destructors?

Isaac To kkto at
Sat Jun 12 16:42:48 CEST 2004

>>>>> "David" == David Bolen <db3l at> writes:

    David> I'm not sure if RAII is intended to also cover non-stack based
    David> objects, in terms handing ownership of the object reference
    David> equating transferring ownership of the resource.  Certainly the
    David> classic example is the stack based approach.

One can do it in C++ using auto_ptr.  The basic use case looks like this:

#include <memory>
#include <iostream>
using namespace std;

struct base_t {
	virtual ~base_t() { cout << "Destroying base_t" << endl; }
	// something complicated

struct derived_t: public base_t {
	~derived_t() { cout << "Destroying derived_t" << endl; }

base_t *base_factory() {
	return new derived_t;

void f() {
	auto_ptr<base_t> p(base_factory()); // heap allocated, function scoped

int main() {
	cout << "Call f" << endl;
	cout << "Continue main" << endl;

Note that in f(), the memory returned by base_factory() is heap allocated,
but function scoped.  I.e., upon leaving function f(), either due to
function return or exception being thrown, the memory is deallocated.  This
is usually used like above, to achieve polymorphism when otherwise one would
want to use a function scoped object.  There is a sense of ownership: when
you do auto-pointer assignment, the original owner lose the ownership, and
the corresponding auto-pointer immediately becomes a NULL pointer.  So

void f() {
	auto_ptr<base_t> p(base_factory());
        auto_ptr<base_t> q = p; // p is now NULL auto-pointer

This makes auto-pointer somewhat difficult to use, and unsuitable for
anything that try to do assignment (e.g., one is committing suicide if one
creates a collection of auto-pointers).  Next standard (C++0x) probably will
introduce reference counted version, hopefully easier to use.


More information about the Python-list mailing list