aboutsummaryrefslogtreecommitdiff
path: root/helium/refcount.cpp
blob: 3378df943ba2b9a7b79c5a97cf405a16cc6b41f0 (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
// Copyright 2006 Google Inc.
// All Rights Reserved.
// Author: <renn@google.com> (Marius Renn)
//

// Local includes
#include "debugging.h"
#include "refcount.h"

// C includes
#include <stddef.h>

using namespace helium;

int ReferenceCounted::number_of_allocations_ = 0;

ReferenceCounted::ReferenceCounted() : ref_count_(new int(1)) {
  number_of_allocations_++;
}

ReferenceCounted::ReferenceCounted(const ReferenceCounted& other) 
  : ref_count_(other.ref_count_) {
  (*ref_count_)++; 
}

ReferenceCounted::~ReferenceCounted() {
  if (ShouldDelete())
    DeleteData();
  else if (ref_count_)
    (*ref_count_)--;
}

void ReferenceCounted::Retain() {
  ASSERT(ref_count_ && (*ref_count_) > 0);
  (*ref_count_)++;
}

void ReferenceCounted::Release() {
  if (!ref_count_) return;
  (*ref_count_)--;
  if ((*ref_count_) == 0) DeleteData();
}

bool ReferenceCounted::ShouldDelete() {
  // Assert that we still have a reference counter, and that it will reach
  // 0 due to this object being deconstructed.
  if (ref_count_ && (*ref_count_ == 1)) {
    *ref_count_ = 0;  // Mark data as deleted
    return true;
  }
  return false;
}

void ReferenceCounted::Realloc() {
  Release();                  // Release old data
  ref_count_ = new int(1);    // Re-init reference counter
  number_of_allocations_++;   // Count the new allocation
}

void ReferenceCounted::DeleteData() {
  delete ref_count_;          // Delete and invalidate reference counter
  ref_count_ = NULL;
  number_of_allocations_--;  
}

void ReferenceCounted::operator=(const ReferenceCounted& other) {
  Release();  // Release old object
  ref_count_ = other.ref_count_;
  Retain();   // Retain new object
}