Can a C++ class determine whether it's on the stack or heap?

后端 未结 15 2189
有刺的猬
有刺的猬 2020-12-13 04:14

I have

class Foo {
....
}

Is there a way for Foo to be able to separate out:

function blah() {
  Foo foo; // on the stack
         


        
15条回答
  •  粉色の甜心
    2020-12-13 04:21

    Nope, it can't be done reliably or sensibly.

    You may be able to detect when an object is allocated with new by overloading new.

    But then what if the object is constructed as a class member, and the owning class is allocated on the heap?

    Here's a third code example to add to the two you've got:

    class blah {
      Foo foo; // on the stack? Heap? Depends on where the 'blah' is allocated.
    };
    

    What about static/global objects? How would you tell them apart from stack/heap ones?

    You could look at the address of the object, and use that to determine if it is within the range that defines the stack. But the stack may be resized at runtime.

    So really, the best answer is that "there's a reason why mark & sweep GC's aren't used with C++". If you want a proper garbage collector, use a different language, one which supports it.

    On the other hand, most experienced C++ programmers find that the need for a garbage collector pretty much vanishes when you learn the necessary techniques for resource management (RAII).

提交回复
热议问题