Boost logo

Boost :

From: Philippe A. Bouchard (philippeb_at_[hidden])
Date: 2002-07-12 10:23:22


Greeting,

I am proposing the attached pointer for whoever find it usefull. It
consists of STL's <memory> with a constant copy constructor. This constant
constructor opens many interesting doors for flexibility benefits: you can
finally build some list< ptr<...> > using push_back(ptr(new type(0)))
without any complains from the compiler. This constructor is allowed to be
constant because the internal pointer is mutable.

The probability of doing an error from the developer when using this format
are a lot smaller than using a real C++ pointer (explicit usage < implicit
destruction) and is a lot more portable than auto_ptr<> (containers).

Regards,

Philippe A. Bouchard
www.fornux.com

/*
    ptr.h

    Copyright (c) 1997
    Silicon Graphics Computer Systems, Inc.

    Copyright (c) 2002
    Philippe A. Bouchard <philippeb_at_[hidden]>

    Permission to copy, use, modify, sell and distribute this software
    is granted provided this copyright notice appears in all copies.
    This software is provided "as is" without express or implied
    warranty, and with no claim as to its suitability for any purpose.
*/

#ifndef __PTR_H
#define __PTR_H

template <class _T>
 class ptr
 {
  mutable _T * _ptr;

 public:
  typedef _T element_type;

  ptr(_T * __p = 0) : _ptr(__p)
  {
  }

  ptr(ptr const & __a) : _ptr(__a.release())
  {
  }

  template <class _T1>
   ptr(ptr<_T1> const & __a) : _ptr(__a.release())
   {
   }

  ptr & operator = (ptr const & __a)
  {
   if (& __a != this)
   {
    delete _ptr;
    _ptr = __a.release();
   }

   return * this;
  }

  template <class _T1>
   ptr & operator = (ptr<_T1> const & __a)
   {
    if (__a.get() != this->get())
    {
     delete _ptr;
     _ptr = __a.release();
    }

    return * this;
   }

  ~ptr()
  {
   delete _ptr;
  }

  _T & operator * () const
  {
   return * _ptr;
  }

  _T * operator -> () const
  {
   return _ptr;
  }

  _T * get() const
  {
   return _ptr;
  }

  _T * release() const
  {
   _T * __tmp = _ptr;
   _ptr = 0;
   return __tmp;
  }

  void reset(_T * __p = 0)
  {
   delete _ptr;
   _ptr = __p;
  }
 };

#endif


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk