Could you expand on that. An example perhaps? I'm not sure I understand the difference between when it is Class scope (would have the array as a member of the class) and when the array is a local variable in a constructor (local scope to that constructor function).
Second option - dynamic array allocation.
Useful if array size unknown at compile time.
class TestClass {
public:
// contsructor with dynamic array creation
TestClass(int array_size) {
array_ptr = new float[array_size];
}
// When using new(), destructor is mandatory
~TestClass() {
delete[] array_ptr;
}
// pointer to array
float* array_ptr = NULL;
};
// Create class instance with 100 elements array
TestClass tc = TestClass(100);
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
This example violates the rule of three/five/zero and will inevitably cause heap corruption when copied or passed by value.
You should never use new/delete in high-level code. Memory management should be handled only by single-purpose classes such as std::unique_ptr or std::vector, allowing you to use the rule of zero for all higher-level code.
When using dynamic memory on a microcontroller, it is also important to be aware of the dangers of memory fragmentation.
Microcontrollers code is not high-level code (in most cases).
I agree with this, but if the lifetime of this class is from the start to the end of the program, then the danger of fragmentation is zero.
In general, I fully agree with the recommendations not to use dynamic memory allocation in microcontrollers, but there are situations when this is the most convenient option. The main thing is to understand what you are doing