auto_ptr for Irrlicht

A forum to store posts deemed exceptionally wise and useful
Post Reply
schick
Posts: 230
Joined: Tue Oct 07, 2003 3:55 pm
Location: Germany
Contact:

auto_ptr for Irrlicht

Post by schick »

Hey guys,

long time ago since my last post. I did some traveling through North America (living in germany by the way). I am just at a friends house and had a look how Irrlicht was growing... nothing to say but amazing.

I will have a look at all the nice features Irrlicht now provides. Thanks everyone for contributing.

But in fact there is a, well, basic thing missing a auto_ptr for IUnknown. So you dont have to care about grabbing and dropping the IUnknown objects anymore. It will be done for you automatically. It can be used nearly the same way as std::auto_ptr.

Here is the code, happy using. If there are some erros please report.

Code: Select all

#ifndef IRR_AUTO_PTR
#define IRR_AUTO_PTR

#include <iosfwd> // std::basic_ostream
#include <cassert> // assert 

namespace irr
{

template <class T> class auto_ptr
{
  private:
    T*  ptr;  
  
  public:
    auto_ptr()
      : ptr(NULL)
    {
    }
    
    ~auto_ptr()
    {
      if(ptr)
        ptr->::irr::IUnknown::drop();
    }
    
    auto_ptr(T* p)
    {
      if(p)
      {
        p->::irr::IUnknown::grab();
        ptr = p;
      }
    }
    
    auto_ptr(const auto_ptr<T>& p)
    {
      if(ptr && p)
        return;
      
      p.ptr->::irr::IUnknown::grab();
      ptr = p.ptr;
    }
    
    auto_ptr<T>& operator=(const auto_ptr<T>& p)
    {
      if(ptr && p)
        return;
      
      p.ptr->::irr::IUnknown::grab();
      ptr = p.ptr;
      
      return *this;
    }  

    T* get() const
    { 
      return ptr; 
    }
    
    T& operator*() const
    {
      assert(ptr);
      return *ptr;
    }
    
    void reset()
    {
      if(ptr)
      {
        ptr->::irr::IUnknown::drop();
        ptr = NULL;
      }
    }
    
    T* operator->() const
    { 
      assert(ptr);  
      return ptr; 
    }
    
    operator bool() const
    {
      return ptr;
    }
    
    bool operator!() const
    {
      return ptr;
    }                      
};

template<class T, class U> inline bool operator==(auto_ptr<T> const & a, auto_ptr<U> const & b)
{
  return a.get() == b.get();
}

template<class T, class U> inline bool operator!=(auto_ptr<T> const & a, auto_ptr<U> const & b)
{
  return a.get() != b.get();
}

template<class T, class U> inline bool operator<(auto_ptr<T> const & a, auto_ptr<U> const & b)
{
  return a.get() < b.get();
}

template<class T> std::ostream & operator<< (std::ostream & os, auto_ptr<T> const & p)
{
  os << p.get();
  return os;
}

} // end namespace irr

#endif // endif IRR_AUTO_PTR

Please send me an e-mail instead of a private message.
Post Reply