The Battle for Wesnoth  1.15.2+dev
reference_counter.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2004 - 2018 by Philippe Plantier <ayin@anathas.org>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #pragma once
16 
17 /**
18  * @file
19  */
20 
21 
22 #include <limits>
23 
24 namespace n_ref_counter {
25 
26 
27 /**
28  @class ref_counter
29  @brief ref_counter is a reference counter. If the counter overflows it stops counting.
30  So any negative count disables reference counting.
31 **/
32 template <typename T_integral> class ref_counter {
33  static_assert(std::numeric_limits<T_integral>::is_signed, "Reference counter must be a signed integer");
34 
35  T_integral count_;
36 
37 public:
38  enum {NEW=0, NOT_COUNTED = -1};
39 
40  explicit ref_counter(T_integral x = 0) : count_(x) {}
41  ref_counter(const ref_counter& a) : count_(a.count_) {}
42  ref_counter & operator=(const ref_counter& a){count_ = a.count_; return *this;}
43 
44  operator T_integral const () const {return count_;}
45 
46  T_integral const set(T_integral const a) { count_=a; return count_; }
47  T_integral const inc(){
48  if (count_ >= 0) { count_ += 1; }
49  return count_; }
50  T_integral const dec(){
51  if( count_ > 0) { count_ -= 1; }
52  return count_; }
53  T_integral const enable_count(){
54  if (count_ < 0) {count_ = 0;}
55  return count_; }
56  T_integral const disable_count(){
57  count_= NOT_COUNTED;
58  return count_; }
59 
60  T_integral const operator++(){return inc();}
61  T_integral const operator++(int){T_integral ret(count_); inc(); return ret;}
62  T_integral const operator--(){return dec();}
63  T_integral const operator--(int){T_integral ret(count_); dec(); return ret;}
64 };
65 
66 
67 }//end namepace
ref_counter(const ref_counter &a)
#define a
ref_counter & operator=(const ref_counter &a)
T_integral const operator++(int)
T_integral const enable_count()
T_integral const disable_count()
T_integral const operator--(int)
ref_counter is a reference counter.