Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.9 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. // These classes let you write your own allocators to be used with new and delete.
  9. // If you have an allocator: VAllocator *pAlloc, you can call new and delete like this:
  10. //
  11. // ptr = VNew(pAlloc) ClassName;
  12. // VDelete(pAlloc, ptr);
  13. //
  14. // Note: allocating and freeing arrays of objects will not work using VAllocators.
  15. #ifndef VALLOCATOR_H
  16. #define VALLOCATOR_H
  17. class VAllocator
  18. {
  19. public:
  20. virtual void* Alloc(unsigned long size)=0;
  21. virtual void Free(void *ptr)=0;
  22. };
  23. // This allocator just uses malloc and free.
  24. class VStdAllocator : public VAllocator
  25. {
  26. public:
  27. virtual void* Alloc(unsigned long size);
  28. virtual void Free(void *ptr);
  29. };
  30. extern VStdAllocator g_StdAllocator;
  31. // Use these to allocate classes through VAllocator.
  32. // Allocating arrays of classes is not supported.
  33. #define VNew(pAlloc) new
  34. #define VDelete(pAlloc, ptr) delete ptr
  35. // Used internally.. just makes sure we call the right operator new.
  36. class DummyAllocatorHelper
  37. {
  38. public:
  39. int x;
  40. };
  41. inline void* operator new(size_t size, void *ptr, DummyAllocatorHelper *asdf)
  42. {
  43. (void)asdf; // Suppress unused-variable compiler warnings.
  44. (void)size;
  45. return ptr;
  46. }
  47. inline void operator delete(void *ptrToDelete, void *ptr, DummyAllocatorHelper *asdf)
  48. {
  49. (void)asdf; // Suppress unused-variable compiler warnings.
  50. (void)ptr;
  51. (void)ptrToDelete;
  52. }
  53. // Use these to manually construct and destruct lists of objects.
  54. template<class T>
  55. inline void VAllocator_CallConstructors(T *pObjects, int count=1)
  56. {
  57. for(int i=0; i < count; i++)
  58. new(&pObjects[i], (DummyAllocatorHelper*)0) T;
  59. }
  60. template<class T>
  61. inline void VAllocator_CallDestructors(T *pObjects, int count)
  62. {
  63. for(int i=0; i < count; i++)
  64. pObjects[i].~T();
  65. }
  66. #endif