How to use other type's memory block?

Can you guys check my way is possible?

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 = new char[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?
Last edited on
First, we need to get memory of sufficient size that is correctly aligned for the object.
And then we need to construct the object in that memory.

This may get you started:

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
50
51
52
53
54
55
56
57
58
#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/align
        if( 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
        }

        else return nullptr ; // pool does not have sufficient aligned memory
    }
};

int main()
{
    memory_pool<128> pool ;

    struct base { virtual ~base() = default ; /* etc. */ virtual void foo() const = 0 ; };

    struct A : base
    {
        explicit A( int v = 10 ) : value(v) {}

        virtual void 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_new
        A* 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
    }
}

http://coliru.stacked-crooked.com/a/735d3086432ab3e7
JLBorges //
Thank you! I didn't know about the placement new.. It is exactly what I want!
Topic archived. No new replies allowed.