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

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

    It is possible if you compare the value of 'this' with the current value of the stack pointer. If this < sp then you have been allocated in the stack.

    Try this out (using gcc in x86-64):

    #include 
    
    class A
    {
    public:
        A()
        {
            int x;
    
            asm("movq %1, %%rax;"
                "cmpq %%rsp, %%rax;"
                "jbe Heap;"
                "movl $1,%0;"
                "jmp Done;"
                "Heap:"
                "movl $0,%0;"
                "Done:"
                : "=r" (x)
                : "r" (this)
                );
    
            std::cout << ( x ? " Stack " : " Heap " )  << std::endl; 
        }
    };
    
    class B
    {
    private:
        A a;
    };
    
    int main()
    {
        A a;
        A *b = new A;
        A c;
        B x;
        B *y = new B;
        return 0;
    }
    

    It should output:

    Stack 
    Heap 
    Stack 
    Stack 
    Heap
    

提交回复
热议问题