OpenTTD
alloc_type.hpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #ifndef ALLOC_TYPE_HPP
13 #define ALLOC_TYPE_HPP
14 
15 #include "alloc_func.hpp"
16 
25 template <typename T>
27 private:
28  T *buffer;
29  size_t count;
30 
31 public:
33  ReusableBuffer() : buffer(nullptr), count(0) {}
35  ~ReusableBuffer() { free(this->buffer); }
36 
44  T *Allocate(size_t count)
45  {
46  if (this->count < count) {
47  free(this->buffer);
48  this->buffer = MallocT<T>(count);
49  this->count = count;
50  }
51  return this->buffer;
52  }
53 
61  T *ZeroAllocate(size_t count)
62  {
63  if (this->count < count) {
64  free(this->buffer);
65  this->buffer = CallocT<T>(count);
66  this->count = count;
67  } else {
68  memset(this->buffer, 0, sizeof(T) * count);
69  }
70  return this->buffer;
71  }
72 
77  inline const T *GetBuffer() const
78  {
79  return this->buffer;
80  }
81 };
82 
88 {
89 public:
91  virtual ~ZeroedMemoryAllocator() {}
92 
98  inline void *operator new(size_t size) { return CallocT<byte>(size); }
99 
105  inline void *operator new[](size_t size) { return CallocT<byte>(size); }
106 
111  inline void operator delete(void *ptr) { free(ptr); }
112 
117  inline void operator delete[](void *ptr) { free(ptr); }
118 };
119 
120 #endif /* ALLOC_TYPE_HPP */
T * ZeroAllocate(size_t count)
Get buffer of at least count times T with zeroed memory.
Definition: alloc_type.hpp:61
const T * GetBuffer() const
Get the currently allocated buffer.
Definition: alloc_type.hpp:77
Functions related to the allocation of memory.
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:44
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition: alloc_type.hpp:26
Base class that provides memory initialization on dynamically created objects.
Definition: alloc_type.hpp:87
size_t count
Number of T elements in the buffer.
Definition: alloc_type.hpp:29
ReusableBuffer()
Create a new buffer.
Definition: alloc_type.hpp:33
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:131
T * buffer
The real data buffer.
Definition: alloc_type.hpp:28
~ReusableBuffer()
Clear the buffer.
Definition: alloc_type.hpp:35