Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce Static Storage at Compile-time

Tags:

c++

c

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.

like image 409
Sam Cristall Avatar asked Jan 07 '14 00:01

Sam Cristall


1 Answers

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 statically, 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.

like image 160
Glenn Teitelbaum Avatar answered Sep 30 '22 05:09

Glenn Teitelbaum