/*
 * SttGuard.h
 *
 *  Created on: 2022年12月15日
 *      Author: SIMTUTAI
 */
#ifndef CORE_SttGuard_H_
#define CORE_SttGuard_H_

#include "core/Defines.h"
#include <atomic>

namespace stt {
class SttGuard {
public:
	SttGuard();
	~SttGuard();
	SttGuard(const SttGuard &other);
	SttGuard& operator=(const SttGuard &other);
	operator bool();

private:
	struct SttGuardHelper {
		SttGuardHelper();

		~SttGuardHelper();
		std::atomic_int *m_ref;
		std::atomic_bool *m_vaild;
	};
	SttGuardHelper *m_guard;
	std::atomic_bool m_isHost;
};

template<typename T>
class SttGuardPtr {
public:
	SttGuardPtr(T *ptr_) :
			m_ptr(ptr_), m_guard(ptr_->guard()) {
	}

	T* operator->() {
		return m_ptr;
	}

	T& operator*() {
		return *m_ptr;
	}

	operator bool() {
		return m_guard;
	}

private:
	T *m_ptr;
	SttGuard m_guard;
};

}

#endif /* CORE_SttGuard_H_ */
