/* **************************************************************************** */ /* */ /* ::: :::::::: */ /* shared_ptr.ipp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: maldavid +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/01/20 10:17:18 by maldavid #+# #+# */ /* Updated: 2024/01/20 10:17:18 by maldavid ### ########.fr */ /* */ /* **************************************************************************** */ namespace unstd { template SharedPtr::SharedPtr(T* ptr) : _ptr(ptr) { typename std::map::iterator it = _refs.find(static_cast(ptr)); if(it == _refs.end()) { _ref = new bits::RefCount(1, 0); _refs[static_cast(ptr)] = _ref; } else { _ref = it->second; _ref->shared++; } } template SharedPtr::SharedPtr(const SharedPtr& rhs) : _ptr(rhs._ptr), _ref(rhs._ref) { if(_ptr && _ref) ++_ref->shared; } template SharedPtr& SharedPtr::operator=(const SharedPtr& rhs) { if(_ptr == rhs._ptr) return *this; safeRelease(); _ptr = rhs._ptr; _ref = rhs._ref; _ref->shared++; return *this; } template SharedPtr::operator bool() const { return _ptr != NULL; } template bool SharedPtr::operator==(const SharedPtr& rhs) { return _ptr == rhs._ptr; } template bool SharedPtr::operator==(T* ptr) { return _ptr == ptr; } template T& SharedPtr::operator*() { return *_ptr; } template T* SharedPtr::operator->() { return _ptr; } template T* SharedPtr::get() { return _ptr; } template void SharedPtr::swap(SharedPtr& rhs) { T* tmptr = _ptr; bits::RefCount* tmpref = _ref; _ptr = rhs._ptr; _ref = rhs._ref; rhs._ptr = tmptr; rhs._ref = tmpref; } template void SharedPtr::reset(T* ptr) { safeRelease(); _ptr = ptr; typename std::map::iterator it = _refs.find(static_cast(ptr)); if(it == _refs.end()) { _ref = new bits::RefCount(1, 0); _refs[static_cast(ptr)] = _ref; } else { _ref = it->second; _ref->shared++; } } template void SharedPtr::safeRelease() { if(_ref == NULL) return; _ref->shared--; if(_ref->shared <= 0) { delete _ptr; _ptr = NULL; delete _ref; _ref = NULL; } } template SharedPtr::~SharedPtr() { safeRelease(); } }