Go Down

Topic: How to specify the size of a class array ? (Read 2 times) previous topic - next topic

PaulS

Quote
String is telling us that kind of functionality is not without problems

The problem is that String instances go out of scope, triggering the destructor which calls delete which calls free(), which has a bug.

By not allowing the array to shrink, you avoid those problems.

Quote
This would be acceptable if the class was only used to declare global variables. In fact, I'd find using such kind of classes to declare local variables strange.

What kind of boards does your class refer to? Are local instances of them reasonable? For instance, Serial is an instance of the HardwareSerial class. There is only one of them, so having anything other than a global instance doesn't make sense. Does your board differ?

tuxduino


Quote
String is telling us that kind of functionality is not without problems

The problem is that String instances go out of scope, triggering the destructor which calls delete which calls free(), which has a bug.

By not allowing the array to shrink, you avoid those problems.


What about growing the array ? Is it safe ?
That would happen when the user would call addBoard() more times than the available slots in the array.


Quote
This would be acceptable if the class was only used to declare global variables. In fact, I'd find using such kind of classes to declare local variables strange.

What kind of boards does your class refer to? Are local instances of them reasonable? For instance, Serial is an instance of the HardwareSerial class. There is only one of them, so having anything other than a global instance doesn't make sense. Does your board differ?


Sorry, I should have called them "items" :) It was just an example. They could be anything from a byte to user-defined objects.
But yes, the use case I have in mind is about using the class to declare global variables only.

PaulS

Quote
What about growing the array ? Is it safe ?
That would happen when the user would call addBoard() more times than the available slots in the array.

Until all available memory was used, it is safe.


drone



I want the user to be able to specify a size. At compile time. Dynamic allocation would mean grow the array as elements are add()ed. String is telling us that kind of functionality is not without problems ;)


A point of note You can't do that with a #define and the Arduino IDE as you intimated earlier.  Only the code in your sketch sees the #define, the library is different compilation unit, and does not see it with the standard arduino make process.  (Unless of course, you ask them to inline your code in their .ino or something.)

!c

tuxduino

Ouch! You're right. For the #define approach to work, either the whole class must be in a single .h file (as in the template case) or the #define'd constant must be in a separate .h file that has to be included by both the sketch and the class header file.

Go Up