I want a class type's memory block, and I want to get the memory block from my memory pool. but it's a char type's memory pool.
Like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
char* pMemoryPool = newchar[128];
size_t head = 0;
// if sizeof(ClassA) is 8bytes
ClassA* pA = (ClassA*)(pMemoryPool + head);
pA->SetSomething(...);
head += 8;
// if sizeof(ClassB) is 12bytes
ClassB* pB = (ClassB*)pMemoryPool + head;
pB->SetSomething(...);
head += 12
// Each class type can have a virtual method table
// and pointer type's variables.
I tried like this, but there are some problems.. like vtable things..
so... HOW TO USE other type's memory block?
#include <iostream>
#include <memory>
#include <algorithm>
template< std::size_t SZ > struct memory_pool
{
char buffer[SZ] ;
char* const end = buffer + SZ ;
char* available_from = buffer ;
// try to get aligned raw memory from the pool suitable to place an object of type T
template < typename T > void* get_memory_for()
{
void* ptr = available_from ;
std::size_t bytes_available = end-available_from ;
// https://en.cppreference.com/w/cpp/memory/alignif( std::align( alignof(T), sizeof(T), ptr, bytes_available ) )
{
// aligned memory is available for an object of type T
available_from = static_cast<char*>(ptr) + sizeof(T) ; // update available_from
return ptr ; // and return the pointer
}
elsereturnnullptr ; // pool does not have sufficient aligned memory
}
};
int main()
{
memory_pool<128> pool ;
struct base { virtual ~base() = default ; /* etc. */ virtualvoid foo() const = 0 ; };
struct A : base
{
explicit A( int v = 10 ) : value(v) {}
virtualvoid foo() const override { std::cout << "A{" << value << ',' << name << "}\n" ; }
int value ;
char name[32] = "anonymous" ;
};
void* p = pool.get_memory_for<A>() ; // get aligned memory for an object of type A
if( p != nullptr ) // if memory is available
{
// https://en.cppreference.com/w/cpp/language/new#Placement_newA* pa = new (p) A(1234567) ; // construct it at p using placement new
base* pbase = pa ;
pbase->foo() ; // use the object (call a virtual function)
pa->A::~A() ; // destroy it
}
}