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