Hello all.
I'm writing a scheduler program for the ESP-01 chip. So far I have a Task class with this structure:
class Task {
public:
void (*callback)();
int started;
int length;
Task(){};
Task(int x, void (*y)()) {
started = millis();
length = x;
callback = y;
}
};
This takes a callback and the amount of time from creation to call it. I'm now trying to make a TaskList class, that will take an array of Tasks and the length of that array. Then, you can call the check() function inside it to check all of those Tasks and see if they're done yet.
class TaskList {
public:
int length;
Task **tasks;
void check() {
Serial.println(this->tasks[0]->length); // this is what always fails
};
TaskList(){};
TaskList(Task *x[], int y) {
tasks = x;
length = y;
}
};
The code compiles without errors, but the device crashes every time I try to read data from tasks inside or outside the TaskList class. I'm new to C++, and very bad with pointers and classes. If somebody could help me out, that would be great.
You know what, I did try your classes even before I asked you to show code, it worked as expected (at least, on arduino nano). But you still didn't provide your full code, as asdf is missing
you are confusing pointers and arrays in one, this results in low readability code, in your case it looks like you would like to use vectors, smart pointers (maybe) and the function object.
You are making global pointers to local variables on the stack, this will result in undefined behavior the moment you exit the setup() function, use 'new' or define your variables globally.
** move your classes to separate header files, and use privatize your class members
TaskList tasks = {
new Task([](){/*function 1*/}),
new Task([](){/*function 2*/})
};
void setup()
{
}
void loop(){
tasks.execute(/*here you could supply additional arguments for your functions*/);
}
In general, if you are new to C++, it is one of the worst things you can do to yourself if you start with function pointers.