C++ Creating an Object for COMPONENT_INIT

Assuming I want to create a class that prints out current time once every 30 second using legato timers. I have this class defined under the name TimerClass. Now when I want to instantiate this class inside COMPONENT_INIT, if I do it like such can I guarantee that the object will bot be destroyed as soon as COMPONENT_INIT is exited or does this function never exit?

	TimerClass timer;

or should this be created as a pointer and dynamically allocated to secure that it never gets destroyed in case COMPONENT_INIT does exit (just in the case of having a main function without a while(1) loop running to guarantee that we never exit:

TimerClass * timer;

	timer = new TimerClass;

Note when i tried doing it without the dynamic allocation i got this error right after start_timer function which causes a fault with the process:

Aug  9 15:18:54 | myTimer[4159] |  | terminate called after throwing an instance of '
Aug  9 15:18:54 | myTimer[4159] |  | std::length_error
Aug  9 15:18:54 | myTimer[4159] |  | '
Aug  9 15:18:54 | myTimer[4159] |  |   what():  
Aug  9 15:18:54 | myTimer[4159] |  | basic_string::_S_create

It is hard to answer you fully correctly without you showing the source code for the timer class also, but I will try anyway.

The COMPONENT_INIT function exits as soon as the functionality in it is executed. Therefore, when you instantiate a class on the stack as you do in the first code example, you are making a variable that essentially only lives while the timer.start_timer() function is executed and is removed from the stack (and very possible overwritten) just after.

The idea behind COMPONENT_INIT is to do something before you start waiting for the events that legato will give you (if you have included any api’s and subscribed for any events). Therefore, as soon as the COMPONENT_INIT function exits, the legato event-loop is started waiting for events from any of the parts of legato that you use.

In short, you will have to use the second example where you allocate the TimerClass on the heap which ensures that it lives until you explicitely deletes it.