Simpatico  v1.10
Memory.h
1 #ifndef UTIL_MEMORY_H
2 #define UTIL_MEMORY_H
3 
4 /*
5 * Util Package - C++ Utilities for Scientific Computation
6 *
7 * Copyright 2010 - 2017, The Regents of the University of Minnesota
8 * Distributed under the terms of the GNU General Public License.
9 */
10 
11 #include <util/global.h>
12 #include <stddef.h>
13 #include <iostream>
14 #include <new>
15 
16 namespace Util
17 {
18 
28  class Memory
29  {
30  public:
31 
38  template <typename Data>
39  static void allocate(Data*& ptr, size_t size);
40 
47  template <typename Data>
48  static void deallocate(Data*& ptr, size_t size);
49 
53  static int nAllocate();
54 
58  static int nDeallocate();
59 
63  static int total();
64 
70  static int max();
71 
72  #ifdef UTIL_MPI
73 
76  static int max(MPI::Intracomm& communicator);
77  #endif
78 
82  static void initStatic();
83 
84  private:
85 
87  static int total_;
88 
90  static int max_;
91 
93  static int nAllocate_;
94 
96  static int nDeallocate_;
97 
98  };
99 
100  /*
101  * Allocate a C array.
102  */
103  template <typename Data>
104  void Memory::allocate(Data*& ptr, size_t size)
105  {
106  if (ptr) {
107  UTIL_THROW("Attempt to allocate to non-null pointer");
108  }
109  try {
110  ptr = new Data[size];
111  total_ += (size*sizeof(Data));
112  ++nAllocate_;
113  if (total_ > max_) max_ = total_;
114  } catch (std::bad_alloc&) {
115  std::cout << "Allocation error" << std::endl;
116  throw;
117  }
118  }
119 
120  /*
121  * De-allocate a C array.
122  */
123  template <typename Data>
124  void Memory::deallocate(Data*& ptr, size_t size)
125  {
126  if (ptr) {
127  delete [] ptr;
128  ptr = 0;
129  total_ -= size*sizeof(Data);
130  ++nDeallocate_;
131  } else {
132  UTIL_THROW("Attempt to de-allocate null pointer");
133  }
134  }
135 
136 }
137 #endif
static int total()
Return total amount of memory currently allocated.
Definition: Memory.cpp:46
static int nAllocate()
Return number of times allocated was called.
Definition: Memory.cpp:34
static void initStatic()
Call this just to guarantee initialization of static memory.
Definition: Memory.cpp:28
File containing preprocessor macros for error handling.
static int nDeallocate()
Return number of times deallocate was called.
Definition: Memory.cpp:40
static void allocate(Data *&ptr, size_t size)
Allocate a C array.
Definition: Memory.h:104
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
Definition: global.h:51
Utility classes for scientific computation.
Definition: accumulators.mod:1
Provides method to allocate array.
Definition: Memory.h:28
static int max()
Return the maximum amount of allocated heap memory thus far.
Definition: Memory.cpp:52
static void deallocate(Data *&ptr, size_t size)
Allocate a C array.
Definition: Memory.h:124