How can an object know if it has been allocated on the stack or the heap? [duplicate]
Possible Duplicate:
How can I tell if an object is statically or dynamically allocated on the constructor?
struct Foo {
Foo ();
};
int main ()
{
Foo foo; // Case A
Foo * p_foo = new Foo (); // Case B
}
Foo :: Foo ()
{
if (allocated_on_stack) {
// Case 开发者_如何学GoA
}
if (allocated_on_heap) {
// Case B
}
}
Can Foo's constructor distinguish these two cases?
The short answer to the question is no.
There are theoretical solutions, for instance you could replace new
(on class or global level) and keep track of all new
allocated pointers and compare to this list to your this
pointer in the constructor.
struct Foo {
Foo ()
{
//Check if `this` is in s_instances
}
void* operator new(size_t size)
{
void* pointer = ::new(size);
s_instances.push_back(pointer);
return pointer;
}
void operator delete (void* pointer)
{
//remove from s_instances and call global delete
}
static std::vector<void*> s_instances;
};
(This code won't catch Foo allocated with new Foo[count]
)
Why do you need this though?
There is no platform independent way. There are few user defined ways. Few of them are,
(1) You may have to put a flag(as a private
variable) and check the same.
struct Foo {
const bool isHeap;
Foo (bool heap = false) : isHeap(heap) {}
};
(2) Keep track inside overloaded new
.
struct Foo {
static set<Foo*> heap;
void* operator new (size_t size)
{
void *p = malloc(size);
heap.insert(<p inside this set>);
}
};
Foo :: Foo ()
{
// check heap.find() for heap allocation
}
Edit: Above solutions offer the way to know if the variable is automatic (generally on stack/data segment) or dynamic (generally on heap segment).
精彩评论