OpenTTD Source 20241224-master-gf74b0cf984
alloc_type.hpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10#ifndef ALLOC_TYPE_HPP
11#define ALLOC_TYPE_HPP
12
13#include "alloc_func.hpp"
14
23template <typename T>
25private:
26 T *buffer;
27 size_t count;
28
29public:
31 ReusableBuffer() : buffer(nullptr), count(0) {}
33 ~ReusableBuffer() { free(this->buffer); }
34
42 T *Allocate(size_t count)
43 {
44 if (this->count < count) {
45 free(this->buffer);
46 this->buffer = MallocT<T>(count);
47 this->count = count;
48 }
49 return this->buffer;
50 }
51
60 {
61 if (this->count < count) {
62 free(this->buffer);
63 this->buffer = CallocT<T>(count);
64 this->count = count;
65 } else {
66 memset(this->buffer, 0, sizeof(T) * count);
67 }
68 return this->buffer;
69 }
70
75 inline const T *GetBuffer() const
76 {
77 return this->buffer;
78 }
79};
80
86{
87public:
89 virtual ~ZeroedMemoryAllocator() = default;
90
96 inline void *operator new(size_t size) { return CallocT<uint8_t>(size); }
97
103 inline void *operator new[](size_t size) { return CallocT<uint8_t>(size); }
104
109 inline void operator delete(void *ptr) { free(ptr); }
110
115 inline void operator delete[](void *ptr) { free(ptr); }
116};
117
118#endif /* ALLOC_TYPE_HPP */
Functions related to the allocation of memory.
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
ReusableBuffer()
Create a new buffer.
T * buffer
The real data buffer.
size_t count
Number of T elements in the buffer.
T * ZeroAllocate(size_t count)
Get buffer of at least count times T with zeroed memory.
const T * GetBuffer() const
Get the currently allocated buffer.
T * Allocate(size_t count)
Get buffer of at least count times T.
~ReusableBuffer()
Clear the buffer.
Base class that provides memory initialization on dynamically created objects.
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition stdafx.h:334