質問

I am developing a library for an embedded system with very little storage in C++. I would like to declare an array for a specific use in one function, however I am unsure if I should declare this in the function as a static array (which would be ideal for my use case), or if I should declare it as a private member in a class. My hesitation to declaring it as a static array in the function, is because I am worried that declaring memory on the fly like that is not a good idea, and should be declared at runtime, however I am still learning so perhaps I am wrong.

Please let me know if you have any suggestions or clarifying questions!

役に立ちましたか?

解決

If you declare the array as static within a function, that is not declaring memory "on the fly". When declaring a variable within a function or class as static, that means that you will have only one copy of that variable which will be shared between all calls to that function or all instances of that class. A dedicated memory location is reserved for that variable up front.

As a static array within a function would be shared between all calls to that function, you need to take special care if multiple calls can be active at the same time, either from multiple threads or through recursion. If either is possible, you would probably be better off with having the array as a (non-static) class member or have it as a non-static variable.

One thing that should really be a last resort option in small embedded systems is to use dynamic allocation with malloc or new (which is also used under the hood by many container classes in the standard library), because it makes it that much harder to tell if you will have enough memory in your device and you suddenly have to think about what to do if you find out at runtime that memory has ran out.

ライセンス: CC-BY-SA帰属
所属していません softwareengineering.stackexchange
scroll top