First off, I know that this problem is basically a no-brainer, and I should ignore the warning and move on with my day, but what is a science without seemingly meaningless questions answered.
The code runs just fine without me changing anything at the top. Everyone who used the web-server library knows the most efficient way to implement is to:
#include <WebServer.h>
WebServer server;
void setup() {
server.begin();
}
void loop() {
server.handleClient();
}
However, I’m interested if it could be declared as non-static/non-global. If it even can happen.
1 Like
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
.
1 Like