I have a structure that I'd like to enforce static storage on. This is a vector type on a DSP, and accidentally declaring it on the stack is a common error for users that causes stack overflow, performance issues or both. As far as I know, this isn't possible, but I'm curious if anyone else knows better.
Example use case:
static Vector64 v1; // OK
static Vector64 v2; // OK
static Vector64 result; // OK
result = v1 * v2; // OK
Vector64 v3; // I would like this to give a compile-time error
Vector64 v4;
result = v3 * v4;
My compiler is Clang/LLVM 3.2, and compiler-specific attributes are fair game.
Since C has no classes, I would pretty much rule this out.
In general, in C++ when you define a class you cannot control whether objects of that type will be defined static
ally, on the stack, on the heap, const
or not const
, in an array or a member of another class. These are choices up to the users of the class.
There are some tricks to keep it off the heap (e.g. playing with operator new
), or only on the heap (e.g. using the generator pattern) but thats not what you want
I would love to see how this is possible, but until such time, I'm pretty sure you cannot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With