Advertisement
EddyLuten

ScopeStack with Macro

Oct 8th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #pragma once
  2.  
  3. #ifndef stack_new
  4. #include <new>
  5. #define stack_new(type, sa, ...) new (sa.AllocateObject<type>()) type(__VA_ARGS__);
  6. #endif
  7.  
  8. #include "linearallocator.h"
  9. #include "./finalizer.h"
  10. #include "./destructorcall.h"
  11. #include "../Async/lock.h"
  12.  
  13. class ScopeStack
  14. {
  15.   LinearAllocator& m_Allocator;
  16.   void* m_RewindCursorPosition;
  17.   Finalizer* m_FinalizerChain;
  18.   Lock m_FinalizerChainLock;
  19.  
  20.   Finalizer* AllocWithFinalizer(size_t size);
  21.   void* GetObjectFromFinalizer(Finalizer* f);
  22.  
  23.   ScopeStack& operator = (const ScopeStack&) { return *this; /* yeah, no. */ };
  24.  
  25. public:
  26.   explicit ScopeStack(LinearAllocator& allocator);
  27.   ~ScopeStack(void);
  28.  
  29.   // I use this to allocate POD types, like your sample.
  30.   void* Allocate(unsigned int size);
  31.  
  32.   // I use this one in conjunction with stack_new(), so it's till not entirely template
  33.   // free, but you won't need to create a specialization for each constructor.
  34.   template<class T>
  35.   T* AllocateObject(void)
  36.   {
  37.     auto finalizer = AllocWithFinalizer(sizeof(T));
  38.     auto result = (T*)GetObjectFromFinalizer(finalizer);
  39.     finalizer->function = &DestructorCall<T>;
  40.  
  41.     m_FinalizerChainLock.Acquire();
  42.     {
  43.       finalizer->chain = m_FinalizerChain;
  44.       m_FinalizerChain = finalizer;
  45.     }
  46.     m_FinalizerChainLock.Release();
  47.  
  48.     return result;
  49.   }
  50. };
  51.  
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement