/********************************************************
 *  ██████╗  ██████╗████████╗██╗
 * ██╔════╝ ██╔════╝╚══██╔══╝██║
 * ██║  ███╗██║        ██║   ██║
 * ██║   ██║██║        ██║   ██║
 * ╚██████╔╝╚██████╗   ██║   ███████╗
 *  ╚═════╝  ╚═════╝   ╚═╝   ╚══════╝
 * Geophysical Computational Tools & Library (GCTL)
 *
 * Copyright (c) 2023  Yi Zhang (yizhang-geo@zju.edu.cn)
 *
 * GCTL is distributed under a dual licensing scheme. You can redistribute 
 * it and/or modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation, either version 2 
 * of the License, or (at your option) any later version. You should have 
 * received a copy of the GNU Lesser General Public License along with this 
 * program. If not, see <http://www.gnu.org/licenses/>.
 * 
 * If the terms and conditions of the LGPL v.2. would prevent you from using 
 * the GCTL, please consider the option to obtain a commercial license for a 
 * fee. These licenses are offered by the GCTL's original author. As a rule, 
 * licenses are provided "as-is", unlimited in time for a one time fee. Please 
 * send corresponding requests to: yizhang-geo@zju.edu.cn. Please do not forget 
 * to include some description of your company and the realm of its activities. 
 * Also add information on how to contact you by electronic and paper mail.
 ******************************************************/

#ifndef _GCTL_SPTR_H
#define _GCTL_SPTR_H

namespace gctl
{
	//模板类作为友元时要先有声明
	template <typename T> class smart_ptr;

	//辅助类
	template <typename T>
	class ref_ptr
	{
	private:
		//该类成员访问权限全部为private，因为不想让用户直接使用该类
		//定义智能指针类为友元，因为智能指针类需要直接操纵辅助类
		friend class smart_ptr<T>;
		ref_ptr() : p(nullptr), count(0) {}
		//构造函数的参数为基础对象的指针
		ref_ptr(T *ptr) : p(ptr), count(1) {}
		//析构函数
		~ref_ptr() {delete p;}
		//引用计数
		int count;
		//基础对象指针
		T *p;
	};

	//智能指针类
	template <typename T>
	class smart_ptr
	{
	public:
		smart_ptr() : rp(new ref_ptr<T>()) {}
		smart_ptr(T *ptr) : rp(new ref_ptr<T>(ptr)) {} //构造函数
		smart_ptr(const smart_ptr<T> &sp) : rp(sp.rp) {++rp->count;} //复制构造函数
		smart_ptr &operator=(const smart_ptr<T>& rhs) //重载赋值操作符
		{
			++rhs.rp->count; //首先将右操作数引用计数加1，
			if (--rp->count == 0) //然后将引用计数减1，可以应对自赋值
				delete rp;
			rp = rhs.rp;
			return *this;
		}

		T &operator *() //重载*操作符
		{
			return *(rp->p);
		}

		T *operator ->() //重载->操作符
		{
			return rp->p;
		}

		~smart_ptr() //析构函数
		{
			if (--rp->count == 0) //当引用计数减为0时，删除辅助类对象指针，从而删除基础对象
			{
				delete rp;
			}
		}

		T *get()
		{
			return rp->p;
		}
	private:
		ref_ptr<T> *rp; //辅助类对象指针
	};
};

#endif //_GCTL_SPTR_H