1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3// See the LICENSE file in the project root for more information.
4
5#ifndef _DEFAULTALLOCATOR_H_
6#define _DEFAULTALLOCATOR_H_
7
8// The "DefaultAllocator" class may be used by classes that wish to
9// provide the flexibility of using an "IAllocator" may avoid writing
10// conditionals at allocation sites about whether a non-default
11// "IAllocator" has been provided: if none is, they can simply set the
12// allocator to DefaultAllocator::Singleton().
13class DefaultAllocator: public IAllocator
14{
15 static DefaultAllocator s_singleton;
16
17public:
18 void* Alloc(size_t sz)
19 {
20 return ::operator new(sz);
21 }
22
23 void* ArrayAlloc(size_t elemSize, size_t numElems)
24 {
25 ClrSafeInt<size_t> safeElemSize(elemSize);
26 ClrSafeInt<size_t> safeNumElems(numElems);
27 ClrSafeInt<size_t> sz = safeElemSize * safeNumElems;
28 if (sz.IsOverflow())
29 {
30 return NULL;
31 }
32 else
33 {
34 return ::operator new(sz.Value());
35 }
36 }
37
38 virtual void Free(void * p)
39 {
40 ::operator delete(p);
41 }
42
43 static DefaultAllocator* Singleton()
44 {
45 return &s_singleton;
46 }
47};
48
49#endif // _DEFAULTALLOCATOR_H_
50