summaryrefslogtreecommitdiff
path: root/libcutl/cutl/static-ptr.hxx
blob: 6c907c83fa60895404f7126e99a50264ee2eee31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// file      : cutl/static-ptr.hxx
// copyright : Copyright (c) 2009-2013 Code Synthesis Tools CC
// license   : MIT; see accompanying LICENSE file

#ifndef CUTL_STATIC_PTR_HXX
#define CUTL_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 // CUTL_STATIC_PTR_HXX