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

 Copyright 2012 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 *************************************/

// File Counted.h
// Baudouin Raoult - ECMWF Dec 98

#ifndef Counted_H
#define Counted_H

// Headers
// #ifndef   machine_H
// #include <machine.h>
// #endif

#include "inc_iostream.h"

// Forward declarations

//class ostream;
// typedef class _Pvts os_typespec; // Remove if not persistant

// 

class Counted {
public:

// -- Exceptions
	// None

// -- Contructors

	Counted();

// -- Destructor


// -- Convertors
	// None

// -- Operators
	// None

// -- Methods

	void attach();
	void detach();

// -- Overridden methods
	// None

// -- Class members
	// None

// -- Class methods
	// None

	// Uncomment for persistent, remove otherwise
	// static os_typespec* get_os_typespec();

protected:

	virtual ~Counted(); // Change to virtual if base class

// -- Members
	// None

// -- Methods
	
	virtual void print(ostream&) const; // Change to virtual if base class	

// -- Overridden methods
	// None

// -- Class members
	// None

// -- Class methods
	// None

private:

// No copy allowed

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

// -- Members

	int count_;

// -- Methods
	// None

// -- Overridden methods
	// None

// -- Class members
	// None

// -- Class methods
	// None

// -- Friends

	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

