> urticator.net

  About This Site
> Domains

> Computers

  Concepts for Persistent Objects
  Language Design Principles
> Miscellaneous

> An Owning Pointer
  Finalization in Java
  What Is Lambda?
  Hierarchical Namespaces
  How I Learned to Write Comments

An Owning Pointer

Here's a small but extremely useful C++ class, which I call an “owning pointer”. The idea is that the pointer owns the object it points to—that is, the pointer is responsible for the object, and will destroy it when the pointer is destroyed.

This class is nothing new or profound, it is just another example of the general category of smart pointers. Reference-counting pointers are perhaps the most common kind of smart pointer, but those have a big defect, which is that they require the pointed-to object to carry a reference count inherited from a common base class—in short, they are intrusive. Owning pointers do not have this defect.

template<type TYPE>
class Own
   TYPE* ptr;

   // copying and assignment not allowed
   Own(const Own& o) {};
   Own& operator=(const Own& o) { return *this; };
   Own() { ptr = NULL; };
   Own(TYPE* a_ptr) { ptr = a_ptr; };

  ~Own() { if (ptr != NULL) delete ptr; };

   void put(TYPE* a_ptr)
      if (ptr != NULL) throw [something];

      ptr = a_ptr;

   TYPE* get() // not const
      if (ptr == NULL) throw [something];

      TYPE* result = ptr;
      ptr = NULL;
      return result;

   TYPE* operator->() { return  ptr; };
   TYPE& operator* () { return *ptr; };

   operator TYPE*() { return ptr; };

For the detail-minded, there are a couple of points worth noting.

First, although it might seem like you'd want to have two sets of operator overloads, const ones returning const values and non-const ones returning non-const values, I think it would actually be incorrect to do so. The reason you'd want such things would be so you could have function arguments of type const Own<TYPE>; the trick is that owning pointers cannot be copied, and so cannot be passed as arguments at all. Instead, you would use arguments of type const TYPE*.

The other notable point is that in real code you wouldn't want the throw statements to be inline, as they are here. The obvious solution would be to hide each of the throw statements inside a static function—and since this is a template class, you'd want them to be static functions on a parent class, or perhaps free functions. Even better, you could declare a two-function interface and let the parent class hold a static interface pointer, then you wouldn't be locked into a particular set of exception classes.


  See Also

  Finalization in Java

@ April (2000)