I'm trying to make a mechanism that could tell where the object of the class is allocated.
Thought about making a flag in the class, but it's not possible to set a value because object's lifetime is not started during the call of "new" operator.
Is it possible in C++ to tell if an object is on stack or heap (runtime)?
There is no portable way to do this, but if we assume you have a limited amount of system types where you are going to do this on, you could try the following:
Take the address of some local variable in main (or other "low in the callstack"). Store this in a global variable, lets call
Then take the address of a local variable in your function that you are checking in, let's call it
Now, if we have a
char *obj = reinterpret_cast<char *>(object_in_test);, then:
if (obj > stacktop && obj < stackbase) on_stack = true; else on_stack = false;
Note that there are SEVERAL flaws with this:
<in the if.
not on stack.
I fully expect to have to delete this answer as it will be downvoted by language lawyers, despite the disclaimer below.