summaryrefslogtreecommitdiff
path: root/src/inc/defaultallocator.h
blob: ee342dff8ba64faae9c4ac4b2d2a6f214e755228 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#ifndef _DEFAULTALLOCATOR_H_
#define _DEFAULTALLOCATOR_H_

// The "DefaultAllocator" class may be used by classes that wish to
// provide the flexibility of using an "IAllocator" may avoid writing
// conditionals at allocation sites about whether a non-default
// "IAllocator" has been provided: if none is, they can simply set the
// allocator to DefaultAllocator::Singleton().
class DefaultAllocator: public IAllocator
{
    static DefaultAllocator s_singleton;

public:
    void* Alloc(size_t sz)
    {
        return ::operator new(sz);
    }

    void* ArrayAlloc(size_t elemSize, size_t numElems)
    {
        ClrSafeInt<size_t> safeElemSize(elemSize);
        ClrSafeInt<size_t> safeNumElems(numElems);
        ClrSafeInt<size_t> sz = safeElemSize * safeNumElems;
        if (sz.IsOverflow())
        {
            return NULL;
        }
        else
        {
            return ::operator new(sz.Value());
        }
    }

    virtual void Free(void * p)
    {
        ::operator delete(p);
    }

    static DefaultAllocator* Singleton()
    {
        return &s_singleton;
    }
};

#endif // _DEFAULTALLOCATOR_H_