aboutsummaryrefslogtreecommitdiff
path: root/libcutl/static-ptr.hxx
diff options
context:
space:
mode:
authorKaren Arutyunov <karen@codesynthesis.com>2020-12-16 20:29:05 +0300
committerKaren Arutyunov <karen@codesynthesis.com>2021-02-24 16:40:04 +0300
commit8e761289a2446367267c6c0d9a26e734f0f78306 (patch)
treefb495d8c18801f271d124ee48731f10df396ca89 /libcutl/static-ptr.hxx
parent4c8104756b92b9fa16b3a725e8a6aa620dfd606e (diff)
Get rid of legacy build systems and rename cutl/ to libcutl/
Diffstat (limited to 'libcutl/static-ptr.hxx')
-rw-r--r--libcutl/static-ptr.hxx73
1 files changed, 73 insertions, 0 deletions
diff --git a/libcutl/static-ptr.hxx b/libcutl/static-ptr.hxx
new file mode 100644
index 0000000..d5750d4
--- /dev/null
+++ b/libcutl/static-ptr.hxx
@@ -0,0 +1,73 @@
+// file : libcutl/static-ptr.hxx
+// license : MIT; see accompanying LICENSE file
+
+#ifndef LIBCUTL_STATIC_PTR_HXX
+#define LIBCUTL_STATIC_PTR_HXX
+
+#include <cstddef> // std::size_t
+
+namespace cutl
+{
+ // This class template implements Jerry Schwarz's static
+ // initialization technique commonly found in iostream
+ // implementations.
+ //
+ // The second template argument is used to make sure the
+ // instantiation of static_ptr is unique.
+ //
+ template <typename X, typename ID>
+ class static_ptr
+ {
+ public:
+ static_ptr ()
+ {
+ if (count_ == 0)
+ x_ = new X;
+
+ ++count_;
+ }
+
+ ~static_ptr ()
+ {
+ if (--count_ == 0)
+ delete x_;
+ }
+
+ private:
+ static_ptr (static_ptr const&);
+
+ static_ptr&
+ operator= (static_ptr const&);
+
+ public:
+ X*
+ operator-> () const
+ {
+ return x_;
+ }
+
+ X&
+ operator* () const
+ {
+ return *x_;
+ }
+
+ X*
+ get () const
+ {
+ return x_;
+ }
+
+ private:
+ static X* x_;
+ static std::size_t count_;
+ };
+
+ template <typename X, typename ID>
+ X* static_ptr<X, ID>::x_ = 0;
+
+ template <typename X, typename ID>
+ std::size_t static_ptr<X, ID>::count_ = 0;
+}
+
+#endif // LIBCUTL_STATIC_PTR_HXX