Roc Toolkit internal modules
Roc Toolkit: real-time audio streaming
iallocator.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Roc authors
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7  */
8 
9 //! @file roc_core/iallocator.h
10 //! @brief Memory allocator interface.
11 
12 #ifndef ROC_CORE_IALLOCATOR_H_
13 #define ROC_CORE_IALLOCATOR_H_
14 
15 #include "roc_core/attributes.h"
16 #include "roc_core/panic.h"
17 #include "roc_core/stddefs.h"
18 
19 namespace roc {
20 namespace core {
21 
22 //! Memory allocator interface.
23 class IAllocator {
24 public:
25  virtual ~IAllocator();
26 
27  //! Allocate memory.
28  //! @returns
29  //! pointer to a maximum aligned uninitialized memory at least of @p size
30  //! bytes or NULL if memory can't be allocated.
31  virtual void* allocate(size_t size) = 0;
32 
33  //! Deallocate previously allocated memory.
34  virtual void deallocate(void*) = 0;
35 
36  //! Destroy object and deallocate its memory.
37  template <class T> void destroy(T& object) {
38  object.~T();
39  deallocate(&object);
40  }
41 };
42 
43 } // namespace core
44 } // namespace roc
45 
46 //! Placement new for core::IAllocator.
47 //! @note
48 //! nothrow forces compiler to check for NULL return value before calling ctor.
49 inline void* operator new(size_t size,
51  return allocator.allocate(size);
52 }
53 
54 //! Placement new[] for core::IAllocator.
55 //! @note
56 //! nothrow forces compiler to check for NULL return value before calling ctor.
57 inline void* operator new[](size_t size,
59  return allocator.allocate(size);
60 }
61 
62 //! Placement delete for core::IAllocator.
63 //! @note
64 //! Compiler calls this if ctor throws in a placement new expression.
65 template <class T>
66 inline void operator delete(void* ptr, roc::core::IAllocator& allocator)ROC_ATTR_NOTHROW {
67  allocator.deallocate(ptr);
68 }
69 
70 //! Placement delete[] for core::IAllocator.
71 //! @note
72 //! Compiler calls this if ctor throws in a placement new[] expression.
73 template <class T>
74 inline void operator delete[](void* ptr,
76  allocator.deallocate(ptr);
77 }
78 
79 #endif // ROC_CORE_IALLOCATOR_H_
Memory allocator interface.
Definition: iallocator.h:23
virtual void * allocate(size_t size)=0
Allocate memory.
GCC attributes.
Root namespace.
void destroy(T &object)
Destroy object and deallocate its memory.
Definition: iallocator.h:37
Commonly used types and functions.
virtual void deallocate(void *)=0
Deallocate previously allocated memory.
#define ROC_ATTR_NOTHROW
Function never throws.
Definition: attributes.h:16
Panic function.