aboutsummaryrefslogtreecommitdiffstats
path: root/fsa/src/vespa/fsamanagers/refcountable.h
blob: de89bf9ccfc597b33a9b025aa13d895c528aac28 (plain) (blame)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * @author  Peter Boros
 * @date    2004/08/20
 * @version $Id$
 * @file    refcountable.h
 * @brief   Reference countable template
 */

#pragma once

#include "mutex.h"

namespace fsa {

// {{{ class RefCountable

/**
 * @class RefCountable
 * @brief Reference countable template
 *
 * Subclass this template, and use the addReference and removeReference
 * methods to keep track of how many references the object has. When
 * the last reference is removed, the object blows up (well, destroys
 * itself).
 */
template <typename T>
class RefCountable
{
protected:

  /** Reference count */
  int      _refCount;

  /** Lock */
  Mutex    _sequencerLock;


  /**
   * @brief Destroy the object
   *
   * @return True.
   */
  virtual bool destroy(void)
  {
    delete this;
    return true;
  };

private:

  /** Unimplemented private copy constructor. */
  RefCountable(const RefCountable &original);
  /** Unimplemented private assignment operator. */
  const RefCountable& operator=(const RefCountable &original);

public:

  /**
   * @brief Constructor
   */
  RefCountable(void)
    : _refCount(0),
      _sequencerLock()
  {
  }

  /**
   * @brief Destructor
   */
  virtual ~RefCountable(void) {}

  /**
   * @brief Increase reference count.
   */
  virtual void addReference(void)
  {
    _sequencerLock.lock();
    _refCount++;
    _sequencerLock.unlock();
  }

  /**
   * @brief Decrease reference count, and destroy object if no
   *        references are left.
   *
   * @return True if the object was destroyed.
   */
  virtual bool removeReference(void)
  {
    bool destroyed = false;

    _sequencerLock.lock();
    _refCount--;

    if(_refCount<1){
      _sequencerLock.unlock();
      destroyed = destroy();
    }
    else{
      _sequencerLock.unlock();
    }
    return destroyed;
  }

};

// }}}

} // namespace fsa