Page 1 of 1

Memory allocation for C++ classes

Posted: Fri Jul 12, 2013 11:20 am
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

Re: Memory allocation for C++ classes

Posted: Fri Jul 12, 2013 12:51 pm
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

Re: Memory allocation for C++ classes

Posted: Fri Jul 12, 2013 1:19 pm
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