Well you can trigger the constructor execution at different places.
You could e.g. have WebServer *server;
and then allocate the object using server = new WebServer();
in setup()
and use server->...
everywhere. If the constructor throws an exception, you should be able to catch it with try-catch.
Further by using placement new
, you can even new
the object in a pre-given buffer space (should be sizeof(WebServer
) of course), so no actual heap memory is used at all.
Or, allocate the object on the stack of a function and make sure execution never leaves the function; once the variable scope is left, the object is deallocated. You can e.g. allocate it setup()
, followed by your own while(true) { own_loop(&server); }
loop to make sure execution never leaves setup()
. When using anything with a watchdog, you might also need to reset the watchdog if that’s something that’s done by the Arduino core between the execution of loop
.