zeusUnnamed repository; edit this file 'description' to name the repository. |
git clone Unknown |
Log | Files | Refs |
policy_smartptr.cpp (1931B)
0 #include <iostream>
1 #include <utility>
3 template <class T> struct DeleteByOperator {
4 template <class U> using rebind = DeleteByOperator<U>;
6 void operator()(T *p) const { delete p; }
7 };
9 template <class P> struct NoRelease {
10 template <class U> using rebind = NoRelease<U>;
11 };
13 struct NoDebug {
14 template <class T> static void constructed(const T *p) {}
15 template <class T> static void deleted(const T *p) {}
16 };
18 template <class T, class DeletionPolicy = DeleteByOperator<T>,
19 template <class...> class ReleasePolicy = NoRelease,
20 class DebugPolicy = NoDebug>
21 class SmartPtr
22 : private DeletionPolicy,
23 public ReleasePolicy<SmartPtr<T, DeletionPolicy, ReleasePolicy>> {
24 T *m_p;
26 public:
27 using deletion_policy = DeletionPolicy;
28 using release_policy =
29 ReleasePolicy<SmartPtr<T, DeletionPolicy, ReleasePolicy>>;
30 using debug_policy = DebugPolicy;
32 explicit SmartPtr(T *p = nullptr,
33 DeletionPolicy &&deletion_policy = DeletionPolicy())
34 : DeletionPolicy(std::move(deletion_policy)), m_p(p) {
35 DebugPolicy::constructed(m_p);
36 }
38 ~SmartPtr() {
39 DebugPolicy::deleted(m_p);
40 DeletionPolicy::operator()(m_p);
41 }
43 template <typename U>
44 using rebind = SmartPtr<U, typename DeletionPolicy::template rebind<U>,
45 ReleasePolicy, DebugPolicy>;
46 };
48 template <class P> struct WithRelease {
49 template <class U> using rebind = WithRelease<U>;
51 void release() { static_cast<P *>(this)->m_p = nullptr; }
52 };
54 struct Debug {
55 template <class T> static void constructed(const T *p) {
56 std::cout << "Constructed SmartPtr for object"
57 << static_cast<const void *>(p) << std::endl;
58 }
60 template <class T> static void deleted(const T *p) {
61 std::cout << "Deleted SmartPtr for object" << static_cast<const void *>(p)
62 << std::endl;
63 }
64 };
66 int main() {
67 const auto p = SmartPtr(new int(5));
69 return 0;
70 }