Memory allocation for C++ classes

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
MathiasP
Posts: 4
Joined: Mon Jun 03, 2013 4:24 pm

Memory allocation for C++ classes

Post by MathiasP »

Hello,

I'm wondering if anyone has the same problem ... I'm using C++ for my application and want to instantiate some classes at startup.
What class I have to instantiate depend on a configuration.

In a non-embedded system I would definitely use new to create an instance. But what would you recommend here in an embedded system with ChibiOS?

My first thought was to use the ChibiOS allocator and call the constructor like this:
CanProtocol* protocol = (CanProtocol*) chCoreAlloc(sizeof(CanProtocol));
*protocol = CanProtocol();

But unfortunately the vtable pointer for this instance will not be initialized with this way.

Has anyone faced this problem yet? How would you solve it?

Best regards
Mathias
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Memory allocation for C++ classes

Post by Giovanni »

Hi,

Probably you have to override the "new" operator and implement it using the core allocator, this way the instance would be initialized correctly. Never tried it however.

Giovanni
MathiasP
Posts: 4
Joined: Mon Jun 03, 2013 4:24 pm

Re: Memory allocation for C++ classes

Post by MathiasP »

Hi Giovanni,

thank you for your suggestion, overriding new works fine (why didn't I to hit on this idea) ...

Code: Select all

void* operator new (size_t size)
   {
    void *p = chCoreAlloc(sizeof(CanProtocol));
    return p;
   }


Meanwhile I found another solution: placement new
I looks like this:

Code: Select all

#include <new> // important

...

CanProtocol* protocol  = (CanProtocol*) chCoreAlloc(sizeof(CanProtocol));
new (protocol) CanProtocol();

This creates an instance of a class at a specific memory location.

Best regards
Mathias
Post Reply