2018-10-10 09:53:07 +00:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "Assertions.h"
|
2018-12-19 21:28:09 +00:00
|
|
|
#include "StdLibExtras.h"
|
2018-10-10 09:53:07 +00:00
|
|
|
|
|
|
|
namespace AK {
|
|
|
|
|
2018-12-19 21:28:09 +00:00
|
|
|
template<class T>
|
2019-05-28 09:53:16 +00:00
|
|
|
constexpr auto call_will_be_destroyed_if_present(T* object) -> decltype(object->will_be_destroyed(), TrueType {})
|
2018-12-19 21:28:09 +00:00
|
|
|
{
|
|
|
|
object->will_be_destroyed();
|
2019-05-28 09:53:16 +00:00
|
|
|
return {};
|
2018-12-19 21:28:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
constexpr auto call_will_be_destroyed_if_present(...) -> FalseType
|
|
|
|
{
|
2019-05-28 09:53:16 +00:00
|
|
|
return {};
|
2018-12-19 21:28:09 +00:00
|
|
|
}
|
|
|
|
|
2019-01-01 01:38:09 +00:00
|
|
|
template<class T>
|
2019-05-28 09:53:16 +00:00
|
|
|
constexpr auto call_one_retain_left_if_present(T* object) -> decltype(object->one_retain_left(), TrueType {})
|
2019-01-01 01:38:09 +00:00
|
|
|
{
|
|
|
|
object->one_retain_left();
|
2019-05-28 09:53:16 +00:00
|
|
|
return {};
|
2019-01-01 01:38:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
constexpr auto call_one_retain_left_if_present(...) -> FalseType
|
|
|
|
{
|
2019-05-28 09:53:16 +00:00
|
|
|
return {};
|
2019-01-01 01:38:09 +00:00
|
|
|
}
|
|
|
|
|
2019-03-16 11:47:19 +00:00
|
|
|
class RetainableBase {
|
2018-10-10 09:53:07 +00:00
|
|
|
public:
|
|
|
|
void retain()
|
|
|
|
{
|
2018-12-19 21:28:09 +00:00
|
|
|
ASSERT(m_retain_count);
|
|
|
|
++m_retain_count;
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
2018-12-19 21:28:09 +00:00
|
|
|
int retain_count() const
|
2018-10-10 09:53:07 +00:00
|
|
|
{
|
2018-12-19 21:28:09 +00:00
|
|
|
return m_retain_count;
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
protected:
|
2019-05-28 09:53:16 +00:00
|
|
|
RetainableBase() {}
|
2019-03-16 11:47:19 +00:00
|
|
|
~RetainableBase()
|
2018-10-10 09:53:07 +00:00
|
|
|
{
|
2018-12-19 21:28:09 +00:00
|
|
|
ASSERT(!m_retain_count);
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
2019-03-16 12:48:56 +00:00
|
|
|
void release_base()
|
|
|
|
{
|
|
|
|
ASSERT(m_retain_count);
|
|
|
|
--m_retain_count;
|
|
|
|
}
|
|
|
|
|
2018-12-19 21:28:09 +00:00
|
|
|
int m_retain_count { 1 };
|
2018-10-10 09:53:07 +00:00
|
|
|
};
|
|
|
|
|
2019-03-16 11:47:19 +00:00
|
|
|
template<typename T>
|
|
|
|
class Retainable : public RetainableBase {
|
|
|
|
public:
|
|
|
|
void release()
|
|
|
|
{
|
2019-03-16 12:48:56 +00:00
|
|
|
release_base();
|
2019-03-16 11:47:19 +00:00
|
|
|
if (m_retain_count == 0) {
|
|
|
|
call_will_be_destroyed_if_present(static_cast<T*>(this));
|
|
|
|
delete static_cast<T*>(this);
|
|
|
|
} else if (m_retain_count == 1) {
|
|
|
|
call_one_retain_left_if_present(static_cast<T*>(this));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-10-10 09:53:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
using AK::Retainable;
|