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

后端 未结 15 2137
有刺的猬
有刺的猬 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:41

    To answer your question, a reliable way (assuming your aplication isn't using more thant one thread), assuming that everithing wich is not contained by your smart pointer isn't on the heap :

    -> Overloading new, so that you ca store a list of all blocs allocated, with the size of each block. -> When the constructor of your smart pointer, search in wich block your this pointer belong. If it isn't in any block, you can say it's "on the stack" (actualy, it means it's not managed by you). Otherwise, you know where and when your pointer was allocated (if you wan't to look for orphan pointers and lasily free memory, or things like that..) It do not depend from the architechture.

    0 讨论(0)
  • 2020-12-13 04:42

    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)

    0 讨论(0)
  • 2020-12-13 04:45

    I am not positive what you are asking, but overriding the new operator may be what you are trying to do. As the only safe way to create an object on the heap in C++ is to use the new operator, you can differentiate between objects that exist on the heap versus other forms of memory. Google "overloading new in c++" for more information.

    You should, however, consider if differentiating between the two types of memory is really necessary from inside the class. Having an object behave differently depending upon where it is stored sounds like a recipe for disaster if you are not careful!

    0 讨论(0)
提交回复
热议问题