I have a low-level embedded application, where I have some relatively large const, global, static arrays (lookup tables and such). The compiler (or linker) stores them in Flash memory rather than in RAM, since they are const.
Now, I have a class that needs to be initialized with one such array. It will use the data from that array throughout the lifetime of the class object.
My question is: how can I safely pass a pointer to this global, static array to the object, while preventing mistakenly passing an array with a short lifetime rather than a static one?
For example, consider the naive implementation that doesn't protect from incorrect initialization:
class Interpolator
{
public:
Interpolator(const float table[], int size);
float interpolate(float x); // uses 'table' data member
private:
const float* table;
int size;
};
Interpolator::Interpolator(const float table[], int size) :
table(table), size(size)
{
}
const float table1[] = {1.0, 2.0, 42.0 /* a few thousand more */ };
void main()
{
Interpolator interpolator1(table1, sizeof(table1) / sizeof(float));
float x = interpolator1.interpolate(17.0); // OK
float* table2 = new float[1024];
// ... calculate and fill in values in table2 ...
Interpolator interpolator2(table2, 1024); // how to prevent this usage?
delete[] table2; // incorrectly assume the object created a copy for itself and the delete is safe...
float y = interpolator2.interpolate(17.0); // ERROR, undefined behavior
}
How do I prevent the second instantiation in the example? perhaps through constexpr somehow, or some clever usage of templates...?
Notes:
I realize that the problem here is that my class doesn't conform to RAII. However, under the constraints explained above (use a large static array from Flash memory), I don't see how I can make it conform to RAII.
Copying the data from the static array to a local data member in the object is out of the question - a single array may literally be larger than my whole RAM, which is only tens of kB in size.
I will have multiple instances of the class, multiple static data tables, and several instances of the class may be initialized with the same static data table.
Any idea for a design pattern that enforces safety here?
thanks!
interpolator2andtable2, why prevent it? (If one cannot, then there may be much more problem here and there, like invalid iterators)