zeus

Unnamed repository; edit this file 'description' to name the repository.
git clone Unknown
Log | Files | Refs

commit e6f07a97f55c4d4f1f6e31bb7012fe60fb21acc1
parent aa505b60b28bf9baaaa6df40fe24ebcb9d743f22
author Dimitrije Dobrota < mail@dimitrijedobrota.com >
date Tue, 13 May 2025 21:00:18 +0200

Policy based design with different techniques

Diffstat:
A policy_smartptr.cpp | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

1 files changed, 71 insertions(+), 0 deletions(-)


diff --git a/ policy_smartptr.cpp b/ policy_smartptr.cpp

@@ -0,0 +1,71 @@

#include <iostream>
#include <utility>

template <class T> struct DeleteByOperator {
template <class U> using rebind = DeleteByOperator<U>;

void operator()(T *p) const { delete p; }
};

template <class P> struct NoRelease {
template <class U> using rebind = NoRelease<U>;
};

struct NoDebug {
template <class T> static void constructed(const T *p) {}
template <class T> static void deleted(const T *p) {}
};

template <class T, class DeletionPolicy = DeleteByOperator<T>,
template <class...> class ReleasePolicy = NoRelease,
class DebugPolicy = NoDebug>
class SmartPtr
: private DeletionPolicy,
public ReleasePolicy<SmartPtr<T, DeletionPolicy, ReleasePolicy>> {
T *m_p;

public:
using deletion_policy = DeletionPolicy;
using release_policy =
ReleasePolicy<SmartPtr<T, DeletionPolicy, ReleasePolicy>>;
using debug_policy = DebugPolicy;

explicit SmartPtr(T *p = nullptr,
DeletionPolicy &&deletion_policy = DeletionPolicy())
: DeletionPolicy(std::move(deletion_policy)), m_p(p) {
DebugPolicy::constructed(m_p);
}

~SmartPtr() {
DebugPolicy::deleted(m_p);
DeletionPolicy::operator()(m_p);
}

template <typename U>
using rebind = SmartPtr<U, typename DeletionPolicy::template rebind<U>,
ReleasePolicy, DebugPolicy>;
};

template <class P> struct WithRelease {
template <class U> using rebind = WithRelease<U>;

void release() { static_cast<P *>(this)->m_p = nullptr; }
};

struct Debug {
template <class T> static void constructed(const T *p) {
std::cout << "Constructed SmartPtr for object"
<< static_cast<const void *>(p) << std::endl;
}

template <class T> static void deleted(const T *p) {
std::cout << "Deleted SmartPtr for object" << static_cast<const void *>(p)
<< std::endl;
}
};

int main() {
const auto p = SmartPtr(new int(5));

return 0;
}