/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#ifndef Counted_H
#define Counted_H

#include <iostream>

using namespace std;

class Counted 
{
public:  
	Counted();

	void attach();
	void detach();
	int count() {return count_;}

protected:
	virtual ~Counted(); // Change to virtual if base class
	virtual void print(ostream&) const; // Change to virtual if base class	

private:
	Counted(const Counted&);
	Counted& operator=(const Counted&);

	int count_;

	friend ostream& operator<<(ostream& s,const Counted& p)
		{ p.print(s); return s; }
	friend class CountedGC;
};

inline void destroy(Counted**) {}

template<class T>
class Handle {
	T* ptr_;
public:
      
	Handle(T* ptr = 0) : ptr_(ptr) 
		{ if(ptr_) ptr_->attach(); }

	virtual ~Handle()   
		{ if(ptr_) ptr_->detach(); }

	Handle(const Handle<T>& other): ptr_(other.ptr_) 
		{ if(ptr_) ptr_->attach(); }

	Handle<T>& operator=(const Handle<T>& other) 
	{
		if(ptr_ != other.ptr_)
		{
			if(ptr_) ptr_->detach();
			ptr_ = other.ptr_;
			if(ptr_) ptr_->attach();
		}
		return *this;
	}

	T* operator->() const { return ptr_; }
	T& operator*()  const { return *ptr_; }

	operator T*() const { return ptr_; }

	bool operator<(const Handle<T>& other) const
		{ return ptr_ < other.ptr_; }
	
};

#endif