I have
class Foo { .... }
Is there a way for Foo to be able to separate out:
function blah() { Foo foo; // on the stack }
and
function blah() { Foo foo* = new Foo(); // on the heap }
I want Foo to be able to do different things depending on whether it's allocated on the Stack or the Heap.
Edit:
Alof of people have asked me "why do this?"
The answer:
I'm using a ref-counted GC right now. However, I want to have ability to run mark & sweep too. For this, I need to tag a set of "root" pointers -- these are the pointers on the stack. Thus, for each class, I'd like to know whether they're in the stack or in the heap.
Stack is a linear data structure whereas Heap is a hierarchical data structure. Stack memory will never become fragmented whereas Heap memory can become fragmented as blocks of memory are first allocated and then freed. Stack accesses local variables only while Heap allows you to access variables globally.
If char charArray[50]; is defined at file scope (outside of all functions) or is static , it's not going to be on the stack, it's going to be a global preallocated at program's start variable. If it's not static and is defined at function scope, it's going to be on the stack.
Memory in a C/C++/Java program can either be allocated on a stack or a heap.
in C, variables are allocated and freed using functions like malloc() and free() the heap is large, and is usually limited by the physical memory available. the heap requires pointers to access it.
A hacky way to do it:
struct Detect { Detect() { int i; check(&i); } private: void check(int *i) { int j; if ((i < &j) == ((void*)this < (void*)&j)) std::cout << "Stack" << std::endl; else std::cout << "Heap" << std::endl; } };
If the object was created on the stack it must live somewhere in the direction of the outer functions stack variables. The heap usually grows from the other side, so that stack and heap would meet somewhere in the middle.
(There are for sure systems where this wouldn't work)
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